+4 votes
in Operating Systems by (60.0k points)
I want to run some bash commands sequentially. However, before running the following command, I want to ensure that the previous command ran successfully. Is there any way to check the success or failure of a bash command?

1 Answer

+2 votes
by (354k points)
selected by
 
Best answer

The return value of any bash command is stored in $?. If its value is 0, it means the command executed successfully; otherwise, there was some error in execution.

Here is an example. I am running my SQL queries in this example.

psql -d dbname -f myqueries.sql
if [ $? -eq 0 ]; then
    echo "SQL finished"
else
    echo "SQL failed"
    exit 1
fi


...