交互式Shell脚本

我如何创build一个简单的Shell脚本来请求来自用户的简单input,然后只运行与预定义选项关联的命令,例如

IF "ON" Backup Server ELSEIF "OFF" Delete Backups ELSEIF "GREY" Send Backups ENDIF 

你可以通过read从用户获得输入,你可以使用一个case ... esac块做不同的事情。

读作为它的参数,它将存储它的值的​​变量的名称

 read foo 

将从用户处获取一个vaue并将其存储在$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 

来源请点击这里来源