Path: utzoo!attcan!uunet!seismo!sundc!pitstop!sun!decwrl!labrea!rutgers!mailrus!ncar!tank!oddjob!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.unix.questions Subject: shell &&, || constructs Keywords: exit status Message-ID: <13810@mimsy.UUCP> Date: 2 Oct 88 05:06:02 GMT References: <5651@sgistl.SGI.COM> <3741@boulder.Colorado.EDU> <703@necis.UUCP> <826@philmds.UUCP> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 55 In article <826@philmds.UUCP> leo@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@mimsy.umd.edu Path: uunet!mimsy!chris