-1

i have been looking at this for an hour without figuring out what the problem is. The else statement is not working for some reason.

#!/bin/bash
if [ $#=3 ]
then
echo $*
else
echo "error" 1>&2
exit
fi
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

1 Answers1

3

The problem is in the line:

if [ $#=3 ]

As you have no spaces around =, it is necessarily doing:

if [ -n $#=3 ]

test which will always be true as =3 is always there, hence the else will never be triggered.

You need to use spaces around =:

if [ $# = 3 ]

Also use double quotes on variable expansion to avoid word splitting and pathname expansion, not strictly necessary in case of $# though.

heemayl
  • 56,300
  • @AnhMinhTran No problem. If the answer helped, please mark it as accepted by clicking the tick mark on the left of the answer so that this issue can be marked as solved. – heemayl Sep 26 '16 at 07:22