Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash if statement not working properly

I have a bash statement to test a command line argument. If the argument passed to the script is "clean", then the script removes all .o files. Otherwise, it builds a program. However, not matter what is passed (if anything), the script still thinks that the argument "clean" is being passed.

#!/bin/bash
if test "`whoami`" != "root" ; then
    echo "You must be logged in as root to build (for loopback mounting)"
    echo "Enter 'su' or 'sudo bash' to switch to root"
    exit
fi
ARG=$1
if [ $ARG == "clean" ] ; then
    echo ">>> cleaning up object files..."
    rm -r src/*.o
    echo ">>> done. "
    echo ">>> Press enter to continue..."
    read
else
    #Builds program
fi
like image 813
Kookerus Avatar asked Sep 20 '25 09:09

Kookerus


1 Answers

Answer for first version of question

In bash, spaces are important. Replace:

[ $ARG=="clean" ]

With:

[ "$ARG" = "clean" ]

bash interprets $ARG=="clean" as a single-string. If a single-string is placed in a test statement, test returns false if the string is empty and true if it is non-empty. $ARG=="clean" will never be empty. Thus [ $ARG=="clean" ] will always return true.

Second, $ARG should be quoted. Otherwise, if it is empty, then the statement reduces to `[ == "clean" ] which is an error ("unary operator expected").

Third, it is best practices to use lower or mixed case for your local variables. The system uses upper-case shell variables and you don't want to accidentally overwrite one of them.

Lastly, with [...], the POSIX operator for equal, in the string sense, is =. Bash will accept either = or == but = is more portable.

like image 122
John1024 Avatar answered Sep 22 '25 05:09

John1024