Home » 2016 » May » 11 » An example to understand bash exit code $? in linux.

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.

shankys:~> date
Wed May 11 06:50:07 CEST 2016

shankys:~> echo $?
0

shankys:~> date 9
date: invalid date `9'

shankys:~> echo $?
1                <--(some error occured in previous command i.e. date 9)

 

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.

shankys:~> datee
-bash: datee: command not found

shankys:~> echo $?
127

shankys:~> datee
-bash: datee: command not found

shankys:~> if [ $? -eq 0 ] || [ $? -eq 127 ];then echo 'something'; else echo 'elsething'; fi

elsething
shankys:~> datee
-bash: datee: command not found

shankys:~> if [ $? -eq 0 -o $? -eq 127 ]; then echo 'something'; else echo 'elsething'; fi
something

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.

 

 
 

Category: Open System-Linux | Views: 1638 | Added by: shanky | Tags: bash exit code, $?, last command check, exit code | Rating: 5.0/1

Related blogs


You may also like to see:


[2016-03-17][Open System-Linux]
Some amazing command shortcuts in Linux
[2014-04-22][Open System-Linux]
xmllint : a command line xml tool to view and find errors in XML file
[2019-09-27][Open System-Linux]
How to generate private/public key from PEM file With PuttyGen
[2015-06-08][Open System-Linux]
CHAGE command in LINUX
[2017-01-21][Open System-Linux]
Useful tips and tricks while working in Linux.

Total comments: 0
ComForm">
avatar