1

I've seen posts similar to this, where the "command not found" error is thrown because of white space errors in the if statement.

I can't find my white space errors. Where are they? What else could it be?

Basically, if I run test.sh (below) without a flag, the terminal starts shouting rude obscenities like, "Command not found". If I use a flag, it plays nice. I don't want to bribe bash with flags all the time. It's not good for it's long term health.

This is in test.sh:

verbose='false'
aflag=''
bflag=''
sflag=''
files=''
while getopts 'absf:v' flag; do
    case "${flag}" in
        a) aflag='true';;
        b) blag='true' ;;
        s) sflag='true' ;;
        f) files="${OPTARG}" ;;
        v) verbose='true';;
        *) error "Unexpected option ${flag}" ;;
    esac
done

# ======= Below this is where the error gets thrown
if "$sflag" ;
then
  echo "okay" ;
fi
# ======= end error throwing code 

echo "end" # this prints just fine

I run the above script with

$ bash test.sh

and then I get back

test.sh: line 17: : command not found
end

Will someone please give me advice on how to talk bash into behaving rationally?

I'm using a Mac (I don't know if that makes a difference).

  • you compare to nothing the if, and if if is empty "there is no such command" – Ziazis Aug 3 '17 at 14:40
  • What are you trying to check for? You can do if [[ -n $sflag ]]; then to check if the variable is not null or -z to check if it is. – Jesse_b Aug 3 '17 at 14:42
  • Okay. Do you have any suggestions for re-implementation? That would be fantastical. – user243760 Aug 3 '17 at 14:43
  • 1
    I check emptyness using if [ "x$flags" = x ]; then echo empty ; else echo not empty ; fi – Archemar Aug 3 '17 at 14:47
  • 1
    use brackets...and better commands (the ones I suggested :p) – Jesse_b Aug 3 '17 at 14:56
2

The error is that you are passing no flags, so the whole while getopts loop is never run, your $sflag remains empty and, as a result, what bash actually runs is:

if ""; then echo "okay" ; fi

The simplest solution would be to initialize your variables as false:

verbose='false'
aflag='false'
bflag='false'
sflag='false'
files='false'
while getopts 'absf:v' flag; do
    case "${flag}" in
        a) aflag='true';;
        b) blag='true' ;;
        s) sflag='true' ;;
        f) files="${OPTARG}" ;;
        v) verbose='true';;
        *) error "Unexpected option ${flag}" ;;
    esac
done

# ======= Below this is where the error gets thrown
if "$sflag" ;
then
  echo "okay" ;
fi
# ======= end error throwing code 

echo "end" # this prints just fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy