Given that there are no jpg
files in my current working directory, why do the two scripts jpg1.sh
and jpg2.sh
give different results? How to understand the difference? Note that the only difference between the scripts is whether to have double quotes around the $()
command substitution.
$ cat jpg1.sh
#!/bin/bash
if [ "$(ls *.jpg | wc -l)" = 0 ]; then
echo "yes"
else
echo "no"
fi
$ ./jpg1.sh
ls: *.jpg: No such file or directory
no
$ cat jpg2.sh
#!/bin/bash
if [ $(ls *.jpg | wc -l) = 0 ]; then
echo "yes"
else
echo "no"
fi
$ ./jpg2.sh
ls: *.jpg: No such file or directory
yes
Follow-up
I testify that the ticked answer is to the point -- wc -l
has some extra white spaces in its return value. After adding set -x
to both scripts, the difference surfaces for itself.
$ ./jpg1.sh
++ wc -l
++ ls '*.jpg'
ls: *.jpg: No such file or directory
+ '[' ' 0' = 0 ']'
+ echo no
no
$ ./jpg2.sh
++ wc -l
++ ls '*.jpg'
ls: *.jpg: No such file or directory
+ '[' 0 = 0 ']'
+ echo yes
yes
By the way my system is macOS Catalina.