如何创建一个简单的 Shell 脚本,该脚本要求用户提供简单的输入,然后仅运行与预定义选项相关的命令,例如
IF "ON"
Backup Server
ELSEIF "OFF"
Delete Backups
ELSEIF "GREY"
Send Backups
ENDIF
如何创建一个简单的 Shell 脚本,该脚本要求用户提供简单的输入,然后仅运行与预定义选项相关的命令,例如
IF "ON"
Backup Server
ELSEIF "OFF"
Delete Backups
ELSEIF "GREY"
Send Backups
ENDIF
您可以通过从用户那里获取输入,read
并且可以使用case ... esac
块来做不同的事情。
Read 将变量的名称作为它的参数,它将存储它的值
read foo
将从用户那里获取一个值并将其存储在$foo
.
要提示用户输入,您需要使用 echo。
echo "What is your favourite color?"
read color
最后,大多数 shell 脚本都支持 case 运算符。采取的形式
case "value" in
"CHOICE)
# Do stuff
;;
esac
把它们放在一起:
echo "Which choice would you like? \c"
read choice
case "$choice" in
ON)
# Do Stuff
;;
OFF)
# Do different stuff
;;
*)
echo "$choice is not a valid choice"
;;
esac
#!/bin/bash
select choice in "ON" "OFF" "*"; do
case "$choice" in
ON) echo "$choice"; # do something;
break;;
OFF) echo "$choice"; # do something;
break;;
*) echo "$choice other"; # do something;
break;;
esac
done
嗨,有一个简单的例子怎么做
while true; do
read -p 'do you want to continue "y" or "n": ' yn
case $yn in
[Yy]* ) echo 'this program continue '; break;;
[Nn]* ) exit;;
* ) echo 'Please answer yes or no: ';;
esac
done
while true; do
read -p 'press "c" to quit this program: ' c
case $c in
[Cc]* ) exit;;
* ) echo 'for quit this program press "c": ' ;;
esac
done
来源点击这里来源