How to write a script which works with or without arguments?

Several ways; the two most obvious are:

  • Put $1 in double quotes: if [ "$1" = "--test" ]
  • Check for number of arguments using $#

Better yet, use getopts.


You need to quote your variables inside the if condition. Replace:

if [ $1 = "--test" ] || [ $1 = "-t" ]; then

with:

if [ "$1" = '--test' ] || [ "$1" = '-t' ]; then  

Then it will work:

➜ ~ ./test.sh
Not testing.

Always always double quote your variables!


You're using bash. Bash has a great alternative to [: [[. With [[, you don't have to worry whether about quoting, and you get a lot more operators than [, including proper support for ||:

if [[ $1 = "--test" || $1 = "-t" ]]
then
    echo "Testing..."
    testing="y"
else
    testing="n"
    echo "Not testing."
fi

Or you can use regular expressions:

if [[ $1 =~ ^(--test|-t) ]]
then
    echo "Testing..."
    testing="y"
else
    testing="n"
    echo "Not testing."
fi

Of course, proper quoting should always be done, but there's no reason to stick with [ when using bash.