BASH Programming

Is there a TRY CATCH command in Bash?

Bash” does not support the “try/catch” command. However, there are other ways to apply its functionalities, such as the “if/else” statements, “OR” operators, the “trap” command, or the “-x” flag.

The “try-catch” is a programming term used to handle exceptions. In simple words, the “try” block tries to do some work, and if there is an error, such as a file not found, it throws an exception which can be copied into the “catch” block.

This guide explores the approaches that can be used as a substitute for the “try/catch” command.

Check the “Exit Status”

All the commands generate a single-digit value (“0” for “true” and “1” for “false”). It is done using the “set -e” option. This option prompts the Bash to exit immediately if any command in the script exits with a non-zero code. In the below example, the script installs Firefox on the system. Once it is successfully executed, it displays the message “Command Succeeded”, as follows:

#!/bin/bash

set -e

sudo apt install firefox

echo "Command succeeded"

Before executing it, make sure to give it execute permissions (the above script is named “script.sh”) using the chmod command with +x flag:

$ sudo chmod +x script.sh

The above executed command confirms that the execute permissions were granted to the file “script.sh”. However, to execute it, apply the following command:

$ bash script.sh

By looking at the above image, it is evident that the command is successfully executed as the message “command succeeded” is displayed. There could be multiple scenarios where you can use the echo command to check the “exit status” right after the command is executed.

How to Make the “trap” Command Function as TRY CATCH?

The “trap” command works based on the Signals sent to it by the OS or the user (by pressing “CTRL+C” to interrupt the program). It is a trigger that is a response to a specific command. For example, the script below runs until the user presses “CTRL+C”. Once pressed, it will display the message “trap worked” and sleep for “5” seconds before giving back the control to the user:

#!/bin/bash

trap 'echo "trap worked"' INT

(

trap '' INT

sleep 5

echo "done"

) &

wait

The above script is named “script.sh.” Let’s execute it to view the results:

$ bash script.sh

In the above terminal, it is seen that when we pressed “CTRL+C”, it printed “trap worked”, and there can be multiple scenarios where it can be used. For example, in the below script, when the service is running, it will stop and restart that service. Let’s assume the service as “mysql” in this case:

#!/bin/bash

function finish {

echo "service started"

sudo service mysql start

}

trap finish EXIT

echo "service stopped"

sudo service mysql stop

The script is named “script.sh”. Let’s execute it to view the output:

$ bash script.sh

As seen in the above terminal, it first stops the service and then starts it again. If you want to start the service immediately right after it is stopped, press “CTRL+C”:

$ bash script.sh

The above examples are similar to the “try/catch” in such a way that a script with multiple commands takes a long time to execute. You can eliminate it using the “CTRL+Z” shortcut keys, but it will not display the message printed via the “echo” command. But when the “trap” command is used, it is easier to identify which command works fine and which is not.

How to Trace Output Using the “-x Flag” in Bash?

The “-x” flag is used for debugging a bash script. It interprets each line being executed and displays everything in the script. To use it, add a prior “-x” when executing the command, as seen below:

bash -x script.sh

The above image displays the script’s parameters in the same format as it is executed.

How to Force Exit When Error is Detected in Bash?

The “set” is used with “errexit” or “-e” in bash to exit. What it does is the automatic termination of the command when there is an error. This option instructs “Bash” to immediately exit the script when any command returns a non-zero exit status, indicating an error.

Following is an example script in which the system repositories are updated, Python is installed, git is cloned, the requirements for Python are installed and finally, the server is launched, respectively:

#!/bin/bash

sudo apt-get update

sudo apt install git curl python3-pip

git clone https://github.com/example/repo.git

pip3 install -r requirements.txt

python3 app.py

It is named “script.sh”. To execute it, apply the below-stated command, as discussed:

$ bash script.sh

The above provided “Username” and “Password” for GitHub are incorrect, which will cause an error resulting in the script’s termination indicated below:

As seen above, the script is immediately terminated once an error is popped.

Conclusion

The bash scripting does not support the “try/catch” statement like most other coding languages. However, there are other alternatives to apply the same functionality, like checking the “exit status”, applying the “trap” command, or tracing the output with the “-x” flag, which can also be useful. Also, the script can immediately be terminated once an error is popped up by using the “set -e” command. This guide discussed the status of the “try/catch” command in bash and its alternatives.

About the author

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.