所以我有这个脚本,我希望脚本测试第二个条件,如果“if”为false,这是elif测试它是否为真。除非它是假的,它继续并测试下一个elif。基本上是多个“其他”。
#Basically It turns a argument into a variable. Because that can't
#work in an if function.
#What the script is doing is its setting variables for the python script
#What vvTHISvv does is it turns the argument into a variable.
if [[ "$1" != "" ]]; then
VAR="$1"
else
VAR=.
fi
if [[ "$2" != "" ]]; then
VAR2="$2"
else
VAR2=.
fi
if [[ "$3" != "" ]]; then
VAR3="$3"
else
VAR3=.
fi
if [[ ${2} = ${VAR2} ]]
#${2} = ${2}
then
echo "I am condition number 1"
#outputs a number
./script.py "${VAR}" "`cat ${VAR2}` `echo ${VAR3}`"
elif [[ ${3} = "${VAR3}" ]]
#${3} = ${3}
then
echo "I am condition number 2"
#outputs a number
./script.py "${VAR}" "`echo ${VAR2}` `cat ${VAR3}`"
elif [[ ${2} = "${VAR2}" ]] || [[ ${3} = "${VAR3}" ]]
then
echo "I am condition number 3"
#outputs a number
./script.py "${VAR}" "`cat ${VAR2}` `cat ${VAR3}`"
else
echo "I am condition number 4"
#outputs a number
./script.py "${VAR}" "${VAR2} ${VAR3}"
fi
如果我按照第一个条件运行,它就可以运行
I am condition number 1
#*Insert whatever that python script did. Lets say it outputs "2"
但是,如果我按照条件编号2进行测试
I am condition number 1
#*insert a bunch of errors
#related to the fact that its rolling based on the first "if"
它不起作用,只为条件号1滚动。
如果只有两个条件我会把“if”和“else”放在一起,但是你如何用四个条件来做呢。
无论如何VAR和$ {1}都是一样的,为什么一个变量是围绕着./script.py中的条件和参数是同一个事实的原因。并且你不能将这两者彼此相等地设置为IF语句中的条件。
答案 0 :(得分:-1)
使用case
,省略(./script.py
代码以显示逻辑的工作方式):
# Assumes none of the variables contain a '#' -- change to some other
# nonexistent string if needed.
case "$2#$3" in
"${VAR2}#${VAR3}") echo both ;;
"${VAR2}#"*) echo 1st ;;
*"#${VAR3}") echo 2nd ;;
*) echo none ;;
esac
由于只将两个变量与两个相应的字符串进行比较,因此只有四种可能的结果。
case
接受多行代码,就像if
一样。使用问题中的第一个条件,代码将变为:
case "$2#$3" in
"${VAR2}#${VAR3}") echo both ;;
"${VAR2}#"*) echo "I am condition number 1"
./script.py "${VAR}" "$(<${VAR2}) ${VAR3}" ;;
*"#${VAR3}") echo 2nd ;;
*) echo none ;;
esac