Afficher un message
Vieux 01/11/2006, 12h59   #2
Stephane CHAZELAS
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: reversing the if condition in posix shell

2006-11-1, 03:50(-08), Yakov:
> Am I right that 'if ! command; then ' form is not posix (the ! part?) ?


Yes it is POSIX. It is not Bourne, and early versions of ksh
didn't have it. I'm not sure about initial versions of ash.

All the standard shs or modern Unices have it. (note that
Solaris standard sh is not /bin/sh).

> If so, then what are nice ways to reverse the condition in if ? Let's
> assume the command after if is not 'test' otherwise it's easy
> to reverse (test ! ...). I know several ways but none of them satisfy
> me:
>
> 1. mytestcmd; if test $? != 0; then body; fi
> sometimes i don't like that it adds extra line
> 2. if mytestcmd; then : nothing; else body; fi
> adds 2-3 extra lines
> 3. mytestcmd || body
> sometimes fine, sometimes I just prefer the 'if' form
> 4. if ! mytestcmd; then body; fi
> i suspect this is not posix ????
> 5. if test `mytestcmd; echo $?` != 0; then body; fi
> invokes extra subshell

[...]



not() {
"$@"
[ "$?" -ne 0 ]
}

But beware that it works diffently than "!" in the sense that it
only works for simple commands.

not foo | bar

only reverses foo status.

! foo | bar

reverses the "foo | bar" status.

--
Stéphane
  Réponse avec citation
 
Page generated in 0,05853 seconds with 9 queries