交互式Shell脚本 [英] interactive Shell Script
问题描述
我如何创建一个简单的Shell脚本,该脚本要求用户提供简单的输入,然后仅运行与预定义选项相关联的命令,例如
how do I create a simple Shell script that asks for a simple input from a user and then runs only the command associated with the predefined choice, for example
IF "ON"
Backup Server
ELSEIF "OFF"
Delete Backups
ELSEIF "GREY"
Send Backups
ENDIF
推荐答案
您可以通过read
接受用户的输入,也可以使用case ... esac
块来执行不同的操作.
You can take input from a user via read
and you can use a case ... esac
block to do different things.
Read会将其值存储在其中的变量名称作为其参数
Read takes as its argument, the name of the variable into which it will store it's value
read foo
将吸收用户的重视并将其存储在$foo
中.
Will take in a vaue from the user and store it in $foo
.
要提示用户输入,您将需要使用echo.
To prompt the user for input you will need to use echo.
echo "What is your favourite color?"
read color
最后,大多数shell脚本都支持case运算符.格式为
Finally, most shell scripts support the case operator. Which take the form
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
这篇关于交互式Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!