Previous Entry | Next Entry

POSIX shell trivia

  • Nov. 28th, 2007 at 10:06 PM
#!/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

( 8 comments — Leave a comment )
[info]ivazquez wrote:
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.
[info]jasondclinton wrote:
Nov. 29th, 2007 05:13 am (UTC)
[ is expr, hence the hint.
[info]desrt wrote:
Nov. 29th, 2007 06:00 am (UTC)
bad hint. [ is actually test(1).
[info]jasondclinton wrote:
Nov. 29th, 2007 06:03 am (UTC)
I guess I should check more than one shell's manpage before I post trivia. grrr...
[info]beranger_org wrote:
Nov. 29th, 2007 07:52 am (UTC)
this reminds me of another people...
(Anonymous) wrote:
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.
[info]fragglet wrote:
Nov. 29th, 2007 09:40 am (UTC)
Shell scripts
Yet another reason to never use shell scripts for anything serious, ever.
(Anonymous) wrote:
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
( 8 comments — Leave a comment )

Profile

[info]jasondclinton
Jason D. Clinton

Latest Month

December 2009
S M T W T F S
  12345
6789101112
13141516171819
20212223242526
2728293031  

Tags

Powered by LiveJournal.com
Designed by Tiffany Chow