Conditional Logic (if/else)
Concept & Overview
Imagine building a script that processes a CSV report, but it crashes if the report file doesn't actually exist on disk. To prevent errors, we write scripts that make decisions using if/else conditional logic.
- We check conditions using brackets: if [ -f "$1" ]; then ... fi.
- The -f flag checks if a path points to a file, while -d checks if it is a directory. The script branches its actions depending on whether the condition evaluates to true or false.
check_file.sh in your home directory that checks if the filename passed as $1 exists (using if [ -f "$1" ]; then echo "Exists" else echo "Missing" fi). Make it executable and test it on names.txt.Command Syntax Reference
| Command / Syntax | Description |
|---|---|
if [ -f file ]; then ... | Syntax for file existence checks |
Verification Objectives
These conditions will be automatically verified when you run commands inside the interactive terminal simulator:
- ○Create script "check_file.sh"
- ○Implement -f checks inside script
- ○Make script executable
- ○Run the script with "names.txt"
Ready to complete Quest 100?
Test your skills live in the browser terminal with an emulated Linux filesystem, real-time command evaluation, and instant step-by-step hints.