Consolidate multiple if statements in Ksh
Solution 1
Try this:
if [[ $# -eq 4 && "$4" == "PREV" ]]
then
print "yes"
fi
You can also try putting them all together like this:
if [[ $# -eq 4 && "$4" == "PREV" || $# -eq 3 && "$3" == "PREV" ]]
then
print "yes"
fi
Do you just want to check if the last argument is "PREV"? If so, you can also do something like this:
for last; do true; done
if [ "$last" == "PREV" ]
then
print "yes"
fi
Solution 2
'[' is not a grouping token in sh. You can do:
if [ expr ] && [ expr ]; then ...
or
if cmd && cmd; then ...
or
if { cmd && cmd; }; then ...
You can also use parentheses, but the semantics is slightly different as the tests will run in a subshell.
if ( cmd && cmd; ); then ...
Also, note that "if cmd1; then cmd2; fi" is exactly the same as "cmd1 && cmd2", so you could write:
test $# = 4 && test $4 = PREV && echo yes
but if your intention is to check that the last argument is the string PREV, you might consider:
eval test \$$# = PREV && echo yes
Solution 3
Try this :
if [ $# -eq 4 ] && [ "$4" = "PREV" ]
then
print "yes"
fi
footy
Spending time in developing codes and new ideas. I also game a lot. Learning new technologies excite me!
Updated on January 05, 2020Comments
-
footy over 4 years
How can I consolidate the following if statements into a single line?
if [ $# -eq 4 ] then if [ "$4" = "PREV" ] then print "yes" fi fi if [ $# -eq 3 ] then if [ "$3" = "PREV" ] then print "yes" fi fi
I am using ksh.
Why does this give an error?
if [ [ $# -eq 4 ] && [ "$4" = "PREV" ] ] then print "yes" fi
Error:
0403-012 A test command parameter is not valid.
-
William Pursell over 12 yearsNotice that the first example is merely a special case of the 2nd, with the command being '['