How do I ask "if NOT" in shell?

Dave Hitz hitz at auspex.auspex.com
Tue Oct 24 08:21:55 AEST 1989


In article <28381 at shemp.CS.UCLA.EDU> kirkaas at oahu.UUCP (paul kirkaas) writes:
>How can one say "if not" in a shellscript; that is, execute the body of
>the "then" only if the argument of "if" returns a non-zero exit status?
>
>I would like something like:
>
>if ! TESTCOMMAND
>then
>	BODY
>fi

I often define the following in my shell scripts.

	    NOT() {
		if ${1+"$@"}
		then return 1;
		else return 0;
		fi
	    }

Unfortunately, not all shells support functions yet, but for those that
do this works fine.  You can use this just like you requested:

	    if NOT grep foobar /etc/passwd >&-
	    then
		    BODY
	    fi

Picky people may observe that the arguments to NOT get expanded by
the shell twice, but I've never been caught by this.

-- 
Dave Hitz					home: 408-739-7116
UUCP: {uunet,mips,sun,bridge2}!auspex!hitz 	work: 408-970-8970



More information about the Comp.unix.questions mailing list