-1

Hi I have written small shell script, I am not able to understand the behavior of that script. can any one help me to understand that script.

Script:

#!/bin/bash

if [ -z $1 ]
then
   echo "fail"
else
  echo "success"
fi

While executing the script .

./test.sh one

It exuting the else statement instead of main statement , even though its passing the argument.

can any one explain me this behavior to understand

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
msr
  • 37
  • 3

1 Answers1

4

The -z test in bash is checking if a string is an empty (zero length) value.

Since you're passing an argument to the script $1 is not empty and therefore -z $1 evaluates to false, executing the else portion of your script.

Side note: Since you're working with strings I recommend you to quote variables as follows:

if [ -z "$1" ]; then
    echo "String is empty / No argument given"
else
    echo "String is not empty / Argument given"
fi

Edit: As pointed out by user1934428 it's probably better to use [[ instead of [. This, among others, eliminates the need for quoting. See more differences here.

if [[ -z $1 ]]; then
    ...

However, be aware that this is a bash extension and won't work in sh scripts.

confetti
  • 1,062
  • 2
  • 12
  • 27
  • 2
    Also adding... the `[` command is a synonym for the `test` command. You can learn more about the flags available for `test` by looking at it's manual: `man test`. Where you will see `-z STRING the length of STRING is zero` – JNevill Jul 30 '18 at 16:37
  • Hi Jnevill. Thank you for your response – msr Jul 31 '18 at 03:11
  • 1
    @confetti: Wouldn't it maybe better to recommend the `[[ ... ]]` form of the test? We wouldn't have to care about quoting then. – user1934428 Jul 31 '18 at 07:09
  • @user1934428 I've made an edit and added some background information. – confetti Jul 31 '18 at 15:57