0
0
Bash Scriptingscripting~15 mins

Exit codes ($?) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Exit Codes ($?) in Bash Scripts
📖 Scenario: You are writing a simple bash script to run commands and check if they worked correctly. Exit codes help you know if a command succeeded or failed.In real life, this is like checking if a light bulb is working after you install it. If it works, you get a green light (exit code 0). If it doesn't, you get a red light (non-zero exit code).
🎯 Goal: Build a bash script that runs a command, saves its exit code using $?, and prints the exit code to understand if the command succeeded or failed.
📋 What You'll Learn
Create a variable to run a command
Save the exit code of the command using $?
Print the exit code to the terminal
💡 Why This Matters
🌍 Real World
Exit codes are used in scripts to detect errors and decide what to do next, like retrying a command or stopping the script.
💼 Career
Understanding exit codes is essential for writing reliable automation scripts and troubleshooting problems in system administration and DevOps roles.
Progress0 / 4 steps
1
Run a command and save its exit code
Write a line that runs the command ls /tmp and then save its exit code in a variable called exit_code using $?.
Bash Scripting
Need a hint?

Run the command first, then immediately save $? to exit_code.

2
Add a second command and save its exit code
Add a line that runs the command cat /not_exist_file and then save its exit code in a variable called exit_code using $?.
Bash Scripting
Need a hint?

Run the second command and save its exit code just like the first.

3
Print the exit code after the second command
Add a line to print the text Exit code is: followed by the value of the variable exit_code.
Bash Scripting
Need a hint?

Use echo to print the message and the variable.

4
Print exit code after the first command too
Add a line to print the text First command exit code: followed by the exit code of the first command. Save the first command's exit code in a variable called first_exit_code before running the second command.
Bash Scripting
Need a hint?

Save the first exit code before running the second command, then print it.