shell脚本应该在单行输入中采用多个条件,并且应该使用输入字符的一端来执行下一个操作。即。
#!/bin/bash
#Functions are defined here 1 2 3 4 5
echo "choice"
echo
echo "[1] one"
echo "[2] two"
echo "[3] three"
echo "[4] four"
echo "[5] five"
echo
read -p "Enter choice: " ch
if [ "$ch" = "1" ]; then
function_1
else
if [ "$ch" = "2" ]; then
function_2
else
if [ "$ch" = "3" ]; then
function_3
else
if [ "$ch" = "4" ]; then
function_4
else
if [ "$ch" = "5" ]; then
function_5
fi
fi
fi
fi
fi
现在说输入结束表示为' e'因此,如果我执行.sh文件并在"输入选项"
$Enter choice: 1 3 5 e
它应该逐个执行1 3和5功能 怎么做?
答案 0 :(得分:5)
您可以迭代所有选项,直到找到输入的结尾':
read -p "Enter choice: " ch
for choice in $ch; do
[ "$choice" == 'e' ] && break
eval function_$choice
done
注意:eval
将从参数汇编命令,然后通过shell
答案 1 :(得分:1)
你应该迭代你的字符串ch直到" e"出现:
#!/bin/bash
#Functions are defined here 1 2 3 4 5
echo "choice"
echo
echo "[1] one"
echo "[2] two"
echo "[3] three"
echo "[4] four"
echo "[5] five"
echo
read -p "Enter choice: " ch
for i in ${ch}
do
if [ "$i" == "1" ]; then
function_1
else if [ "$i" == "2" ]; then
function_2
else if [ "$i" == "3" ]; then
function_3
else if [ "$i" == "4" ]; then
function_4
else if [ "$i" == "5" ]; then
function_5
else if [ "$i" == "e" ]; then
break
fi
fi
fi
fi
fi
fi
但是mxlian的答案是"更清洁"。我只是更正你的代码..
答案 2 :(得分:0)
如果您将每个输入参数作为选项并使用了getopts即
,那会更好myProg.sh -a aArg -b bArg -c cArg
在myProg.sh中:
while getopts "a:b:c" option
do
case $option in
a) function_1;;
b) function_2;;
c) function_3;;
*) exitFunc "Incorrect argument";; # You need to write exitFunc()
esac
done
这样你可以有一个缺失的选项,即只有选项a和c(没有b)。如果按照自己的方式进行,并且缺少一个参数(或为空),则说参数3,则参数4变为参数3等。