?

Log in

No account? Create an account

Previous Entry | Next Entry

POSIX shell trivia

#!/bin/sh
false
if [ $? = 1 ]
then
	echo $?
fi

The above code block outputs "0". If $? is defined as, "Expands to the status of the most recently executed foreground pipeline," can you define exactly why the output is "0"?

hint: expr test (updated)

Comments

( 6 comments — Leave a comment )
ivazquez
Nov. 29th, 2007 05:01 am (UTC)
Simple. "[" is a command, and it has to evaluate to true (i.e., 0) in order for the body of the if statement to be executed.
jasondclinton
Nov. 29th, 2007 05:13 am (UTC)
[ is expr, hence the hint.
(Deleted comment)
jasondclinton
Nov. 29th, 2007 06:03 am (UTC)
I guess I should check more than one shell's manpage before I post trivia. grrr...
(Deleted comment)
(Anonymous)
Nov. 29th, 2007 08:35 am (UTC)
Re: this reminds me of another people...
$? in shell is just like errno in C and all those weird built-in variables in Perl: If you need it, save it to a different variable first. Always.
GCC should have a -Werrno switch that complains if errno is used for anything but assigning it to something else.
fragglet
Nov. 29th, 2007 09:40 am (UTC)
Shell scripts
Yet another reason to never use shell scripts for anything serious, ever.
(Anonymous)
Nov. 2nd, 2009 12:48 pm (UTC)
its because of the false. it evaluates to a non zero exit status 1. So the return code $? is set to the value of 1 which tests as true in the [ $? = 1 ]. and hence prints 0. Check the debug mode of execution using a '#!/bin/sh -x'


+ false
+ '[' 1 = 1 ']'
+ echo 0
0
( 6 comments — Leave a comment )

Profile

color, uphair, smile
jasondclinton
Jason D. Clinton

Latest Month

September 2011
S M T W T F S
    123
45678910
11121314151617
18192021222324
252627282930 

Tags

Page Summary

Powered by LiveJournal.com
Designed by Tiffany Chow