This tutorial aims to provide a comprehensive understanding of file descriptors and error handling in shell scripts. By the end of this tutorial, you will have a sound knowledge of how to manage file descriptors and effectively handle errors in your scripts.
A basic understanding of shell scripting is required. Familiarity with the command line and simple commands is a plus.
File descriptors are integers that serve as an abstract indicator for accessing files or other input/output resources. The Unix-like operating systems start with three standard file descriptors:
- 0 - Standard Input (stdin)
- 1 - Standard Output (stdout)
- 2 - Standard Error (stderr)
Error handling in scripts involves identifying when a command fails and taking appropriate action. The exit status of a command is zero when the command is successful, and non-zero when it fails.
One of the most common ways to handle errors is to use the set -e
command at the beginning of a script, which causes the shell to exit if any invoked command exits with a non-zero status.
Here's an example of redirecting error messages (stderr) to a file:
command 2> error.txt
In this example, '2' stands for stderr, and '>' is the redirection operator. It redirects the error messages generated by 'command' into a file named 'error.txt'.
Here's an example of a script that exits on the first error:
#!/bin/bash
set -e
# Any command that fails will cause the script to exit immediately
command1
command2
command3
In this script, if command1
, command2
, or command3
fails (i.e., returns a non-zero status), the script will exit immediately.
We've covered the basics of file descriptors and error handling in shell scripts. You've learned how to manipulate file descriptors and how to handle errors in your scripts. As next steps, you can explore more advanced error handling techniques and different ways to manipulate file descriptors.
For more information, you can refer to the following resources:
Now it's time for you to put your knowledge into practice. Here are some exercises:
Solutions
#!/bin/bash
command > out.txt 2> error.txt
This script redirects stdout to 'out.txt' and stderr to 'error.txt'.
#!/bin/bash
command
if [ $? -ne 0 ]; then
echo "The command failed."
fi
In this script, $?
gives the exit status of the last executed command. If it's not zero, the script prints "The command failed.".