在shell中,我想让用户在两个选项中选择一个,然后当 1 或 2 时,用它做一个switch语句。我怎么能这样做呢。
echo "Press [1] to transfer to $drive1"
echo "Press [2] to transfer to $drive2"
read #input somehow?
我已经尝试将第二个回声变成读数。但理想情况下,我想将两个echo
放入此处的文档中,然后将其应用于read
但我无法正确显示这些行。
options <<_EOF_
"Press [1] to transfer to $drive1"
"Press [2] to transfer to $drive2"
_EOF_
read $options -n 1
但我收到错误line 7: options: command not found
答案 0 :(得分:2)
你想做两件事:
这是两个完全独立的操作,您不应该尝试将它们组合在一起。要在此处的文档中撰写邮件,请使用cat
:
cat << EOF
Press [1] to transfer to $drive1
Press [2] to transfer to $drive2
EOF
阅读一个数字:
read -n 1 option
总之:
#!/bin/bash
cat << EOF
Press [1] to transfer to $drive1
Press [2] to transfer to $drive2
EOF
read -n 1 option
echo
echo "You entered: $option"
答案 1 :(得分:2)
你可以做
cat << PROMPT
Press [1] to transfer to $drive1
Press [2] to transfer to $drive2
PROMPT
read -n1 drivenumber
case "$drivenumber" in
1) handle drive 1;;
2) handle drive 2;;
*) handle invalid input;;
esac
这符合您的要求。但是你必须做额外的工作来避免无效的输入:
input=
while true; do
that whole thing
validate_input && break
echo "oh no your input was invalid"
done
此外,为了澄清上面的select
评论,当您想要更改驱动器数量时,使用heredoc隐含的架构有点麻烦。
drives=( "$drive1" "$drive2" )
PS3="Choose a drive to transfer to"
select drive in "${drives[@]}"; do
# really no need for a case statement anymore
do_x_to "$drive"
done
或者你可以走混合路:
while true; do
for i in "${!drives[@]}"; do
printf 'Press [%d] to transfer to %s\n' "$i" "${drives[i]}"
done
read -n1 drive_number
if [[ ! ${drives[drive_number]} ]]; then
echo "invalid drive number" >&2
continue
fi
drive=${drives[drive_number]}
case "$drive" in …
esac
done