BASH is the default shell in GNU/Linux systems. While writing BASH scripts sometimes it become necessary to take action based upon the success of previous command. So how do we do this.
First we need to understand that almost every command that is run once completed returns a exit code, 99% of commands just use 0 for success, 1 for failure. Without getting into other details, lets see how we can use this value.
As I said above any command will return the error code after it has executed. This error value is updated by BASH into a special variable called $? (dollar question mark). One can check this value to find if the command was successful or was a failure.
So lets say you run a command ls, it will run successfully, after this if you say echo $?, it will display 0, as the command runs successfully. Now lets say if you run the same command with the name of a nonexistant file or directory, i.e.
$ ls nonexistantfilefoo
ls: cannot access 'nonexistantfilefoo': No such file or directory
You will get an error similar to above. Now if you immediately check the value of $? it will be non zero, indicating some error.
One very important aspect to remember is that as soon as you run any other command the $? will be updated again, so as soon as you say echo $? the command runs successfully and $? gets updated again.
So how do we use this in a BASH script?
First way would be to immediately use the value of $? in a conditional check. Lets say we have the following script:
#!/bin/bash
cat abc
if [ $? -eq 0 ]
then
echo "File exists"
else
echo "Some error occurred"
fi
What if you want to take more than one action i.e. later on also?
In this case you will have to immediately save the value of $? after the command is run. e.g.
#!/bin/bash
cat abc
my_error=$? #here we store the error/exit code value immediately into variable my_var
if [ $my_error -eq 0 ]
then
echo "File exists"
else
echo "Some error occurred"
fi
In the above example we stored the value in a separate variable and used it later, if required the variable can be still used for other action based on the result of the command in question.
Add new comment