Bash 根据输入参数执行一个或所有条件
我正在编写一个shell脚本,其中基于输入参数,脚本应该执行某些条件。我想将其增强到这样一个程度:如果输入参数为“all”,脚本应该执行脚本中提到的所有可能条件。伪代码控制流程如下所示。我想帮助定义一个条件,当input arg为“all”时,必须执行所有条件 输入Bash 根据输入参数执行一个或所有条件,bash,shell,unix,Bash,Shell,Unix,我正在编写一个shell脚本,其中基于输入参数,脚本应该执行某些条件。我想将其增强到这样一个程度:如果输入参数为“all”,脚本应该执行脚本中提到的所有可能条件。伪代码控制流程如下所示。我想帮助定义一个条件,当input arg为“all”时,必须执行所有条件 输入 ./test.sh <arg1> 输出 ./test.sh <arg1> 命令-1: ./test.sh a 结果-1: Inside a 命令2: ./test.sh b 结果2: Inside
./test.sh <arg1>
输出
./test.sh <arg1>
命令-1:
./test.sh a
结果-1:
Inside a
命令2:
./test.sh b
结果2:
Inside b
命令-3:
./test.sh all
结果-3:
Inside a
Inside b
好的,下面是您所问问题的bash代码:
arg1=$1
if [ "$arg1" == "a" ]; then
echo "Inside a"
elif [ "$arg1" == "b" ]; then
echo "Inside b"
elif [ "$arg1" == "all" ]; then
echo "Inside a"
echo "Inside b"
fi
使用案例陈述:
case $1 in
a) echo "Inside a" ;;
b) echo "Inside b" ;;
all)
echo "Inside a"
echo "Inside b"
;;
*) ;;
esac
我的工作解决方案如下所示:
#!/bin/bash
#set -x
set +e
arg1=$1
# Function Definition
func_a ()
{
echo " Inside a "
}
func_b ()
{
echo " Inside b "
}
# Invoking functions based on input params
if [ "$arg1" = "a" -o "$arg1" = "all" ];
then
func_a
fi
if [ "$arg1" = "b" -o "$arg1" = "all" ];
then
func_b
fi
#EOF
执行结果如下:
bash-4.2$ ./test.sh a
Inside a
bash-4.2$ ./test.sh b
Inside b
bash-4.2$ ./test.sh all
Inside a
Inside b
请不要因为if条件中定义了input
“all”
的方式而使此解决方案具有可扩展性和可维护性。那么,您的问题是,只需给出一些bash代码就可以了吗@Yashyes Dorilds…谢谢,但是考虑每一个<代码>回声<代码>语句作为一个15行代码,我不想在<代码> ELIF [“$ARG1”=“ALL”] < /代码>条件中重复。我想要一个可扩展和易于维护的解决方案。谢谢,但是把每一个<代码> Engule<代码>语句作为一个15行代码,我不想在第三代码> CASE < /Cord>语句中重复。我想要一个可扩展且易于维护的解决方案。您可以将这15行放在一个函数中,并在case块中调用它。在if块或case块中放置15行几乎没有任何区别。