9:44 AM An example to understand bash exit code $? in linux. |
We very often use the inbuilt variable $? in linux to check the status of last command used. To find if the last command is correctly executed, we fire echo $? always. If it return 0, the command is successfully completed else some error occured while executing the command. See below example.
So the conclusion is $? retains the status code depending on the result of most recent command executed. To make it more obvious, we take another example. What is the difference between below two statements: if [ $? -eq 0 ] || [ $? -eq 127 ]; then echo 'something'; and if [ $? -eq 0 -o $? -eq 127 ]; then echo 'something'; See the below example and try to understand.
In normal scenarions, both if statements should yield same result not here. Why?? The reason is the first if statement has [ ] blocks and the left part of it alters the value of $? so the right part of it does not have the original value of $? which means the right part also does not have value as 127 causing print 'elsething' The second if statement comapres $? with 0 or 127 simultaneously without changing the value of $?. So, it matches with the exit code 127 which is the exit code of 'datee' command.
Ideally in this scenario, we must use the second statement to get the correct result. Though in other cases both statements can be used giving same result.
|
|
Related blogs
You may also like to see:
[2014-04-10] | [Open System-Linux] |
SED command for filtering and transforming texts of a file using regular expression |
[2014-11-25] | [Open System-Linux] |
DMESG command in Linux : to display or control kernel ring buffer |
[2016-04-14] | [Open System-Linux] |
AT command in Linux : schedule a task at later time |
[2014-09-26] | [Open System-Linux] |
Traceroute command in Linux |
[2014-10-25] | [Open System-Linux] |
XMLWF command in Linux to check/validate/parse an XML file |
Total comments: 0 | |