交互式Shell脚本



如何创建一个简单的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

相关内容

  • 没有找到相关文章

最新更新