footy
footy

Reputation: 5921

Consolidate multiple if statements in Ksh

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.

Upvotes: 3

Views: 45892

Answers (3)

William Pursell
William Pursell

Reputation: 212374

'[' 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

Upvotes: 3

dogbane
dogbane

Reputation: 274720

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

Upvotes: 3

Ali Ismayilov
Ali Ismayilov

Reputation: 1755

Try this :

if  [ $# -eq 4 ]  && [ "$4" = "PREV" ]
    then
            print "yes"
    fi

Upvotes: 1

Related Questions