Shell user prompt (Y/n)
我只想写一个小的sript来为我的NAS复制一些文件,所以我在shell脚本编写方面经验不足。我知道Linux上的许多命令行工具使用以下sheme进行是/否输入
1 | Are you yure [Y/n] |
其中大写字母表示也将启动的标准操作通过点击enter。这很适合快速使用。
我还想实现类似的功能,但是缓存enter密钥时遇到了一些问题。以下是我迄今为止所得到的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 |
我可以添加任何我想要的,但它不能与enter一起工作。
如果您使用的是
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 ;; |
下面是一个快速解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 |
它的输入验证接受"y"、"y"、"空字符串"或"n"和"n"作为问题[y/n]的有效输入。
1 2 3 4 5 6 7 8 9 10 11 | #!/bin/bash while : ; do # colon is built into bash; and is always true. read -n1 -p"Are you sure? [Y/n]" response echo case"$response" in y|Y|"") echo"files will be moved"; break ;; # Break out of while loop n|N) echo -e"canceled"; break ;; # Break out of while loop *) echo"Invalid option given." ;; esac done |
你应该使用
1 2 3 4 5 6 | read -n1 -p"Are you sure? [Y/n]" response case"$response" in [yY]) echo"files will be moved";; ?) echo"canceled";; esac |
按
1 2 3 | -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 |
由于您提供了选项[Y/N],代码可以更改如下(编辑):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #!/bin/bash while true do echo"Are you sure? [Y/n]?" read response case $(echo ${response:-Y}|tr '[:lower:]' '[:upper:]') in Y|YES) echo"files will be moved!" break ;; N|NO) echo"aborted!" exit ;; *) echo"incorrect selection!" ;; esac done |