Reputation: 13
I wrote the following script in Bash but it is not printing the desired output:
a="abc"
if (test "$a"="$a ") then
echo "true "
else
echo "false "
fi
This script should print false
but it isn't. I'm new to Bash scripting, so can anyone please tell me why it is not printing false
?
Upvotes: 1
Views: 887
Reputation: 183270
You're giving test
only one argument: "$a"="$a "
, which is equivalent to "$a=$a "
. When test
gets only one argument, it evaluates to 0
/true/success if that argument contains at least one character, and to 1
/false/error otherwise. The minimal fix would be to put spaces around the =
, so you're giving it three separate arguments:
if (test "$a" = "$a ") then
but I'd really recommend writing it in a Bashier style:
if [[ "$a" = "$a " ]] then
(Note that the (
and )
in the original version merely cause test
to be run in a subshell, which really serves no purpose at all.)
Upvotes: 3