1

Little explanation necessary: why the hell does this doesn't work?

#!/bin/bash

ker=$1
if [ "$ker" != "iso" ] || [ "$ker" != "om" ] || [ "$ker" != "constbeta" ] ; then
 printf " allowed kernels: iso, om, constbeta \n"
 exit
fi
wait
echo 'anisotropy kernel: ', "$ker"

I have also tried

#!/bin/bash

ker="$1"
if [ $ker != "iso" ] || [ $ker != "om" ] || [ $ker != "constbeta" ] ; then
 printf " allowed kernels: iso, om, constbeta \n"
 exit
fi
wait
echo 'anisotropy kernel: ', "$ker"

I call it like this: $ ./script.sh iso
and I've even tried like this (though I think this doesn't make sense with the scripts above): $ ./script.sh "iso"
I always get allowed kernels: iso, om, constbeta
Many thanks to those who can spot the error.

2 Answers 2

2

because of the logical or ||, you should use and && otherwise the condition is always true thinking to the negation string can't be equals to the three value.

Sign up to request clarification or add additional context in comments.

Comments

1

You've got an irrational condition...

if [ "$ker" != "iso" ] || [ "$ker" != "om" ] || [ "$ker" != "constbeta" ] ; then

If $ker is "iso", then it is not "om" and the condition matches. If $ker is "om" then it is not "iso" and the condition matches. What you want is to OR a list of positive checks and have an "else" condition, rather than OR the negative checks.

if [ "$ker" = "iso" ] || [ "$ker" = "om" ] || [ "$ker" = "constbeta" ] ; then
    : do something useful
else
    : report error
fi

Or, since you're in bash, you could use a "simpler" condition:

if [[ "$ker" =~ ^(iso|om|constbeta)$ ]]; then

Though if you like you could use other constructs:

case "$ker" in
  iso|om|constbeta)
    : this catches our "good" values
    ;;
  *)
    echo "Error" >&2
    exit 1
    ;;
esac

This has the possible benefit of being POSIX compliant.

3 Comments

I get it. thank you both. ps: your second suggestion doesn't work, but I'll figure our
@andrea - Varsågod, that's what we're here for. :) What does the second suggestion do instead of working? Do you get an error?
no, it works. it just doesn't work the way I thought (ie the opposite). I still need to learn bash formatting syntax, I just never have time for that. tak så mycket!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.