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
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

  • @spaceout [[ is bash-specific, [ is POSIX so if you do not need [[ (which is more powerful) then you should stick to [. – Hauke Laging Apr 4 '18 at 9:26
  • or using an old hack, "x"$1 = "x" – Rui F Ribeiro Apr 4 '18 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.