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
  • 66,199
  • 35
  • 114
  • 250
1565986223
  • 103
  • 2
  • Stop referring the TLDP documentation - Follow this [The Bash Wiki hackers](http://wiki.bash-hackers.org/) – Inian Apr 04 '18 at 09:00

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
  • 88,146
  • 18
  • 125
  • 174