Shell user prompt (Y/n)
I just wanted to write a small sript for copying some files for my NAS, so I'm not very experienced in Shell-Scripting. I know that many command line tools on Linux use the following sheme for Yes/No inputs
Are you yure [Y/n]
where the capitalized letter indicates the standard action which would also be started by hitting Enter. Which is nice for a quick usage.
I also want to implement something like this, but I have some trouble with caching the Enter key. Here is what I got so far:
read -p "Are you sure? [Y/n] " response
case $response in [yY][eE][sS]|[yY]|[jJ]|[#insert ENTER codition here#])
echo
echo files will be moved
echo
;;
*)
echo
echo canceld
echo
;;
esac
I can add what ever I want but it just won't work with Enter.
这是一个快速解决方案:
read -p "Are you sure? [Y/n] " response
case $response in [yY][eE][sS]|[yY]|[jJ]|'')
echo
echo files will be moved
echo
;;
*)
echo
echo canceled
echo
;;
esac
If you are using bash
4, you can "pre-seed" the response with the default answer, so that you don't have to treat ENTER
explicitly. (You can also standardize the case of response
to simplify the case
statement.
read -p "Are you sure? [Y/n] " -ei "y" response
response=${response,,} # convert to lowercase
case $response in
y|ye|yes)
echo
echo files will be moved
echo
;;
*)
echo
echo cancelled
echo
;;
You should use read -n1
read -n1 -p "Are you sure? [Y/n] " response
case "$response" in
[yY]) echo "files will be moved";;
?) echo "canceled";;
esac
As per help read
:
-n nchars return after reading NCHARS characters rather than waiting
for a newline, but honor a delimiter if fewer than NCHARS
characters are read before the delimiter
链接地址: http://www.djcxy.com/p/25550.html
上一篇: Linux bash shell脚本提示用户输入并存储在变量中
下一篇: Shell用户提示(Y / n)