trying to use logical or and i must be missing something

greetings,
i am trying to force the user to ensure that $CPUS equals 12 or 24. it cannot be any other value including null. after the expr statement $AMT needs to equal 1 or 2. how i read the line in question is "if $CPUS is zero/null or not equal to 12 or not equal to 24" then issue the message, otherwise continue. what am i not getting here?

if [ "$CODE" = "comsol" ]; then
        if [ -z "$CPUS" ] || [ "$CPUS" != "12" ] || [ "$CPUS" != "24" ]; then
                echo ""
                echo "You must either specify 12 or 24 cpus for code Comsol"
                echo ""
                exit 1
        else
                AMT=$(expr $CPUS / 12)
        fi
RUSAGE="rusage [lic_req_comsol=$AMT:duration=15] span[host=$AMT]"
fi

thanx as always.

For your situation, you must use "&&" (and).

if [ "$CODE" = "comsol" ]; then
        case "$CPUS" in
                ( 12|24 )
                AMT=$(expr $CPUS / 12)
                RUSAGE="rusage [lic_req_comsol=$AMT:duration=15] span[host=$AMT]"
        ;;
                ( * )
                echo ""
                echo "You must either specify 12 or 24 cpus for code Comsol"
                echo ""
        ;;
        esac
fi

thanx as always for any and all help!!

That might actually have been a better way to do it.

The reason your first try didn't work because "or" wasn't really what you wanted. You flipped the logic with the !=, which changes the picture a bit -- a string can't possibly be equal 12 and 24 at the same time! One or the other, or both, will always be false, flipping that makes one or the other always true; and or-ing that produces a statement which is always true no matter what.

To do it with ||:

if [ "$CPUS" = "12" ] || [ "$CPUS" = "24" ]; then
:
else
        ...
fi

I think the -z is superfluous, then, since a null string will never equal 12 or 24.

1 Like

thanx corona688, after your explanation i played around with it a bit and i get it now. it's pretty clear i was going a bit "too far" and over thinking it. i'll stick with my solution above but will keep your tutorial in mind for future reference!

Alternative approach with "case". Also do arithmetic in Shell not with "expr".

if [ "$CODE" = "comsol" ]; then
        case "${CPUS}" in
        "12"|"24")
                AMT=$(( ${CPUS} / 12 ))
                ;;
        *)
                echo "You must either specify 12 or 24 cpus for code Comsol"
                echo ""
                exit 1
                ;;
        esac
RUSAGE="rusage [lic_req_comsol=$AMT:duration=15] span[host=$AMT]"
fi