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

Solution 1:

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.

Solution 2:

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!

Solution 3:

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.

Solution 4:

To test if arguments are present (in general, and do the actions accordingly) This should work:

#!/bin/bash

check=$1

if [ -z "$check" ]; then
  echo "no arguments"
else echo "there was an argument"
fi