1

I try to write a very simple bash script file named bash_script.sh

#!/bin/bash

if [ -z $1 ];then
        echo $1
else
        echo 'no variable'
fi

in the terminal I tried to run ./bash_script.sh hello but the output on the terminal is no variable. What did I do wrong here?

UMR
  • 310
  • 4
  • 16

1 Answers1

7

The -z operator is true if its argument is an empty string. hello is not an empty string, so the else clause is taken.

Probably you meant to say simply

if [[ "$1" ]]; then
    echo "$1"
else
    echo 'no variable'
fi

Notice also when to wrap quotes around a shell variable (basically always, at least until you understand when you might not want to) and the preference for [[ over [ in Bash scripts.

But probably more idiomatically, just check if $# is equal to 1, or larger than zero if you want to allow multiple arguments. This will work the same regardless of whether some of those arguments are empty strings.

For completeness, the way to get your original script to take the if branch would be

./bash_script.sh ''

(or alternatively with double quotes instead of single around the empty argument).

tripleee
  • 175,061
  • 34
  • 275
  • 318