Thursday, March 31, 2005

Bash - Using statements in conditions

To test the success or failure of a command, the general method of scripting is as follows:
#!/bin/bash

some_command
if [ $? -eq 0 ]
then
    # Command executed successfully
else
    # Command execution failed
fi
A better method to do the same is as follows:
#!/bin/bash
if some_command
then
    # Command executed successfully
else
    # Command executed failed
fi
Please note the change in syntax for if between the two statements.
This can be very helpful especially if there is a chance that some line gets added between the command and the if statement. In the former case, we will effectively be checking for the return value of the new statement that has been added. In the latter case, such problems do not come.
Post a Comment