1833566 Members
3265 Online
110061 Solutions
New Discussion

Re: Test Condition

 
SOLVED
Go to solution
panchpan
Regular Advisor

Test Condition

Could you please let me know the difference between [[ $? != 0 ]] and [ $? != 0 ]

Normally, I believe IF $? is not equal to 0 means - success.

Correct me if i am wrong.
9 REPLIES 9
Oviwan
Honored Contributor
Solution

Re: Test Condition

no, if $? equals 0 it means success.

look at this example:
$ cd /etc; echo $?
0
$ cd /nirvana; echo $?
su: /nirvana: not found.
1
Dennis Handly
Acclaimed Contributor

Re: Test Condition

This single brackets is documented under test(1). And you have a slight error in it. $? is an integer, you are doing a string compare with "0", while this will work, the correct form is: [ $? -ne 0 ]

The double bracket form is a ksh/Posix shell new feature. What you are doing there is even more wrong. You are doing pattern matching of an integer with a string. This just happens to work again.

Also "Word splitting and file name generation are not" are not done in [[]].

It also has more conditions and you can use || and && to combine conditions.

>I believe IF $? is not equal to 0 means - success.

Yes but you should use -ne instead.
Dennis Handly
Acclaimed Contributor

Re: Test Condition

>I believe IF $? is not equal to 0 means - success.

Oops, as Oviwan says, I got it backwards.
panchpan
Regular Advisor

Re: Test Condition

Okay - it concludes that if $? != 0 means failed.

Also, what is the meaning of writing 2>&1 i have seen in end of some commands.
spex
Honored Contributor

Re: Test Condition

Hello,

A single-bracket expression calls the test(1) command, while a double-bracket expression uses the shell's built-in evaluation. A double-bracket expression supports wildcards and more operators than the single-bracket version. Perhaps most notably, with double brackets, "&&" and "||" may be used in place of "-a" and "-o".

On any UNIX and UNIX-like platform, an exit status (${?}) of zero indicates success. Conversely, a non-zero exit status usually indicates failure.

PCS
Oviwan
Honored Contributor

Re: Test Condition

yes $? != 0 means failed.

for example
$ cd /nirvana
su: /nirvana: not found.
$ cd /nirvana >/dev/null
su: /nirvana: not found.
$ cd /nirvana >/dev/null 2>&1
...no error msg

2>&1 redirect the error msg (stderr) to /dev/null
panchpan
Regular Advisor

Re: Test Condition

THANKS A LOT !!!
Dennis Handly
Acclaimed Contributor

Re: Test Condition

>PCS: A single-bracket expression calls the test(1) command,

This is incorrect. This is also a shell built in. Using tusc shows no execs.
Dennis Handly
Acclaimed Contributor

Re: Test Condition

>what is the meaning of writing 2>&1

This is described in ksh(1) or sh-posix(1). It basically executes the system call dup2(2) in the shell: dup2(1,2)
Or: X>&Y -> dup2(Y, X)

It closes stderr and duplicates the properties of stdout to stderr.

In Oviwan's example, stdout is /dev/null so stderr is now that too.