我正在编写一个shell脚本,其中该脚本应根据输入参数执行某些条件。我想将其增强到一个点,如果输入参数为“ all”,则脚本应执行脚本中提到的所有可能条件。伪代码控制流程如下所示。我需要帮助来定义条件,当输入arg为“全部”时,必须执行所有条件。
输入
./test.sh <arg1>
算法
if ($arg1 == a)
print " Inside a";
elsif ($arg1 == b)
print " Inside b";
elsif ($arg1 == "all")
print " Inside a";
print " Inside b";
fi
输出
command-1:
./test.sh a
结果1:
Inside a
command-2:
./test.sh b
结果2:
Inside b
command-3:
./test.sh all
结果3:
Inside a
Inside b
答案 0 :(得分:0)
好的,这是您要查询的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
答案 1 :(得分:0)
使用案例说明:
case $1 in
a) echo "Inside a" ;;
b) echo "Inside b" ;;
all)
echo "Inside a"
echo "Inside b"
;;
*) ;;
esac
答案 2 :(得分:0)
适用于我的解决方案如下所示:
#!/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条件中定义输入"all"
的方式使此解决方案可扩展和可维护。