Swi*_*124 9 shell shell-script
我目前正在编写我的第三个 shell 脚本,但遇到了一个问题。到目前为止,这是我的脚本:
#!/bin/bash
echo "choose one of the following options : \
1) display all current users \
2) list all files \
3) show calendar \
4) exit script"
while read
do
case in
1) who;;
2) ls -a;;
3) cal;;
4) exit;;
esac
done
Run Code Online (Sandbox Code Playgroud)
当我尝试运行脚本时,它说:
line2 : unexpected EOF while looking for matching '"'
line14 : syntax error: unexpected end of file.
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
让我们不要忘记select
:
choices=(
"display all current users"
"list all files"
"show calendar"
"exit script"
)
PS3="your choice: "
select choice in "${choices[@]}"; do
case $choice in
"${choices[0]}") who;;
"${choices[1]}") ls -a;;
"${choices[2]}") cal;;
"${choices[3]}") break;;
esac
done
Run Code Online (Sandbox Code Playgroud)
问题是,您的case
陈述缺少主题 - 它应该评估的变量。因此,您可能想要这样的东西:
#!/bin/bash
cat <<EOD
choose one of the following options:
1) display all current users
2) list all files
3) show calendar
4) exit script
EOD
while true; do
printf "your choice: "
read
case $REPLY in
1) who;;
2) ls -a;;
3) cal;;
4) exit;;
esac
done
Run Code Online (Sandbox Code Playgroud)
这里case
使用默认变量$REPLY
,read
当它没有给出任何变量名称时填充(help read
有关详细信息,请参阅)。
还要注意更改:printf
用于在每一轮中显示提示(并且不附加换行符),cat
用于在多行上打印说明,以便它们不会换行并且更易于阅读。