0

Am learning bash and it's confusing how (why) this line of code if [$1 = ]; then works. Can someone please explain.

From bash tuturial here under File re-namer (6th block)

# a quick check to see if any files were given
# if none then it's better not to do anything than rename some non-existent
# files!!

if [$1 = ]; then
    echo "no files given"
    exit 0
fi
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

2

That code is wrong, it does not work if the argument is not empty (and does not begin with whitespace) because [ is not a special character and is not recognised as command if it is not a separate word (that would not even work with [[).

set -x shows you what the shell sees:

set -x
[$1 = ]
    + '[' = ']'

In that case the test result is true because there is a string between [ and ]; it does not matter that it is =.

Tests for a non-empty argument should be done as

[ -n "$1" ] ; echo $?
    + '[' -n '' ']'
    + echo 1

or

[ -z "$1" ] ; echo $?
    + '[' -z '' ']'
    + echo 0

instead

Hauke Laging
  • 90,279