Double ampersand (&&) versus if-then in shell scripts


I tend to prefer using this syntax with tests:

(grep $name /etc/passwd) && echo $name is a valid user

However, having a variable increment upon success does not do what you probably want. For example:

count=0
for name in $list; do
	(grep $name /etc/passwd) && (echo $name is a valid user"; count=$(($count + 1)))
done
echo count is $count

When this is run, count will always be zero. It seems the count within the && line is local to that line. However, changing it to an if-then structure will work:

count=0
for name in $list; do
	if (grep $name /etc/passwd >/dev/null); then
		echo $name is a valid user
		count=$(($count +1))
	fi
done
echo count is $count

Here count will be the number of names that are in the passwd file, as expected.

12/18/2007