shell脚本中有什么方法可以通过编程设置输入行?考虑以下情况。
假设我制作一个脚本来创建一个git分支,在完成分支完成后,我不想以编程方式切换到新的分支,而只需给用户在提示符上显示的命令,因此不必键入命令以切换到新分支,但只有在他想运行显示的命令时只按Enter键。
read -p "Enter your branch name: " N
git branch $N
render-text-on-prompt "git checkout $N"
执行:
$ ./mkbranch
$ Enter your branch name: change-93
$ git checkout change-93 _
bash
无法"预紧"下一个输入缓冲区(与zsh
不同,您可以简单地使用print -z "git checkout $N"
(。您需要让mkbranch
处理输入(并随后执行输入命令(本身。
read -p "Enter your branch name: " N
git branch "$N"
read -e -i "git checkout $N" cmd
eval "$cmd"
-e
通知read
使用readline库输入文本行;-i
选项预加载输入缓冲区。(没有-e
-i
无需任何事情。(
请注意,read -e
本身对bash
语法一无所知,因此没有隐式线连续。这使其与普通的bash
提示完全不同。
另一种选择是简单地询问用户是否想结帐新创建的分支:
read -p "Enter your branch name: " N
git branch "$N"
read -e -i Y -p "Checkout branch $N? (Y/n)"
[[ $REPLY == Y ]] && git checkout "$N"
击中Enter接受预加载的Y,以触发硬编码的``Checkout命令;任何其他命令都跳过它。无论哪种方式,脚本结束并返回常规命令提示。
您可以使用开关来检查用户输入是什么。
function render_text_on_prompt {
if [[ -z ${1} ]]; then # The argument passed into the function is empty/not set
echo "Wrong usage!"
return 1
fi
# Print the argument
echo "${1} - Hit the enter key to run this command or anything else to abort"
read INPUT_STRING
case ${INPUT_STRING} in # Check what the user entered
"") # User entered <enter>
${1}
break
;;
*) # User entered anything but enter
echo "Nothing changed"
break
;;
esac
return 0
}
我希望这有所帮助。
这是一个存根,可以根据需要进行调整:
c="echo foo bar" ; read -p "Run '$c' [Y/n]? " n ;
[ ! "$n" ] || [ "$n" = Y ] || [ "$n" = y ] && $c
如果用户类型 Enter ,y
或Y
,则最后一行将运行命令$c
。示例运行:
Run 'echo foo bar' [Y/n]?
用户hits enter :
foo bar