Michael C. Toren on 20 Feb 2006 03:27:49 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] bash and if


On Sun, Feb 19, 2006 at 03:50:46PM -0500, Jeff Abrahamson wrote:
> The following attempt fails miserably (at the syntax level, for
> obvious reasons):
> 
>     if [ (cmp -s "$f" "$dir2/$b") -a $? == 0 ]; then

There are a few things syntactically wrong with the above, but it is more
important to understand why the intention of the above is wrong.  The
bourne shell's "if <command>" construct runs the specified command, and
if it returns an exit status of zero, executes the associated "then"
block.  There is no need to run a command and to then examine the exit
status to see if it is zero.  Rather, just run the command by itself:

	if cmp -s a b; then ...

> I'd like to be more elegant than a double if, merely on principle:
> 
>     if [ -r "$f" -a -r "$dir2/$b" ]; then
>         if ( cmp -s ... ); then ...

Fortunately you don't have to.  If one of the files does not exist and cmp
returns 2, the "if" statement will not run the "then" block, as the "then"
block is only run if the "if" command returns zero.

HTH,
-mct
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug