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、
$c
或 y
,最后一行将运行命令 Y
。运行示例:
Run 'echo foo bar' [Y/n]?
用户点击Enter:
foo bar
期待是你的朋友。
这使您可以通过编写预期响应脚本来自动与需要用户输入的程序进行交互。
示例:
#!/usr/bin/expect
spawn /path/to/interactive_program
expect "Username:"
send "your_username\r"
expect "Password:"
send "your_password\r"
# Continue with additional interactions as needed
# Wait for the program to finish
expect eof
在此示例中,脚本使用“spawn”命令启动交互式程序,然后使用“expect”等待程序输出中的特定模式(例如“用户名:”或“密码:”)。 “发送”命令用于提供响应。
请注意,使用“expect”进行自动化可能很强大,但可能会产生安全隐患,特别是在处理密码等敏感信息时。应注意安全地处理此类信息。
相关问题在这里: