shell &&, || constructs

Chris Torek chris at mimsy.UUCP
Sun Oct 2 15:06:02 AEST 1988


In article <826 at philmds.UUCP> leo at philmds.UUCP (Leo de Wit) writes:
>command1 || command2               # do command2 only if command1 failed
>command1 && command2               # do command2 only if command1 succeeded
>while command1; do commands; done  # while command1 succeeds do the commands
>until command1; do commands; done  # until command1 succeeds do the commands
>if command1; do commands; done     # if command1 succeeds do the commands
>
>And now we're at it:
>
>set -e    # exit - if the shell's not interactive - as soon as a command fails

With the exception of `set -e', these constructs exist in csh as well,
although the syntax differs:

	command1 || command2
	command1 && command2
	while ({ command1 })
		commands
	end
	while (! { command1 })
		commands
	end
	if ({ command1 }) then
		commands
	endif

The parentheses around { command1 } may sometimes be elided.  But
beware!: the effect of && and || were reversed in the 3BSD C shell,
and are still reversed in some derivative C shells.  (It is fixed
in 4.3BSD; I am not sure how far back the rot goes.)

Regarding `set -e': again, beware!  Old versions of /bin/sh will
exit if the test portion of an `if', `while', or `until' returns
a nonzero status, if `-e' is set.  (These are fixed in 4.3BSD-tahoe.)
In addition, `command1 || command2' will exit if command1 fails.
(It will also exit if command2 fails, but that seems sensible.
I believe SysV's /bin/sh does *not* exit if command2 fails.  If
this is considered correct behaviour, let me know, because I just
`fixed' this to work the way I think seems sensible.)

Incidentally, this bug in the 4BSD `/bin/sh'es accounts for
makefile lines like

	-[ -d ${DESTDIR}${LIBDIR} ] || mkdir ${DESTDIR}${LIBDIR}

where the `-' before the test `[' seems erroneous: it tells make to run
sh without the -e flag, so that the mkdir can happen.  An alternate
workaround is to use

	set +e; [ -d ${DESTDIR}${LIBDIR} ] || mkdir ${DESTDIR}${LIBDIR}

which has the advantage that if mkdir fails, make stops.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.unix.questions mailing list