Linux 在单个文件中接受多个用户输入的Shell脚本
shell脚本应该在单行输入中接受多个条件,并且应该在输入字符的一端执行下一个操作。即Linux 在单个文件中接受多个用户输入的Shell脚本,linux,shell,unix,Linux,Shell,Unix,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" =
#!/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功能
如何做到这一点?您可以迭代所有选项,直到找到“输入结束”:
read -p "Enter choice: " ch
for choice in $ch; do
[ "$choice" == 'e' ] && break
eval function_$choice
done
注意:eval将根据参数组合一个命令,然后通过shell执行该命令。您可以迭代所有选项,直到找到“输入结束”:
read -p "Enter choice: " ch
for choice in $ch; do
[ "$choice" == 'e' ] && break
eval function_$choice
done
注意:eval将根据参数组合一个命令,然后通过shell执行它。您应该在字符串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的答案更清晰。我只是纠正您的代码。您应该在字符串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的答案更清晰。我只是更正了您的代码。如果您将每个输入参数都设置为一个选项并使用getopts ie,那会更好
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。如果您按自己的方式执行,并且有一个参数丢失或为空,比如paramater 3,那么参数4将变为参数3等。如果您将每个输入参数设置为一个选项,并使用getopts ie,则会更好
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。如果您按照自己的方式执行,并且有一个参数丢失或为空,比如paramater 3,那么参数4将变为参数3,以此类推