Using Exit Status Codes
Exit status codes are numerical values returned by a command or script to indicate whether it completed successfully. In Linux and Unix-like systems:
- An exit status of
0
indicates success
- A non-zero exit status (1-255) indicates an error or other exceptional condition
Let's create a script that uses different exit status codes based on certain conditions.
First, create a new script file:
cd ~/project
touch status_codes.sh
Open the file with nano:
nano status_codes.sh
Add the following content:
#!/bin/bash
## Demonstrating exit status codes
## Check if a filename was provided as an argument
if [ $## -eq 0 ]; then
echo "Error: No filename provided"
echo "Usage: $0 <filename>"
## Exit with status 1 (general error)
exit 1
fi
filename=$1
## Check if the file exists
if [ ! -f "$filename" ]; then
echo "Error: File '$filename' not found"
## Exit with status 2 (file not found)
exit 2
fi
## Check if the file is readable
if [ ! -r "$filename" ]; then
echo "Error: File '$filename' is not readable"
## Exit with status 3 (permission denied)
exit 3
fi
## If we get here, everything is fine
echo "File '$filename' exists and is readable"
## Exit with status 0 (success)
exit 0
Save the file (Ctrl+O
, Enter
) and exit nano (Ctrl+X
).
Make the script executable:
chmod +x status_codes.sh
Now, let's test this script with different scenarios.
First, run the script without any arguments:
./status_codes.sh
You should see:
Error: No filename provided
Usage: ./status_codes.sh <filename>
The script exited with status code 1. You can check the exit status of the last command using the special variable $?
:
echo $?
You should see:
1
Now, let's create a test file and run the script again:
echo "This is a test file" > testfile.txt
./status_codes.sh testfile.txt
You should see:
File 'testfile.txt' exists and is readable
Check the exit status:
echo $?
You should see:
0
This indicates that the script completed successfully.
Finally, try with a non-existent file:
./status_codes.sh nonexistent_file.txt
You should see:
Error: File 'nonexistent_file.txt' not found
Check the exit status:
echo $?
You should see:
2
This demonstrates how you can use different exit status codes to indicate different types of errors.