Shell Conditionals with if and test
One objective, which names if, test and [] explicitly. The single most useful thing to understand is that [ is a command - which explains why it needs spaces around it, why the operators are words like -gt, and why an unquoted empty variable produces a syntax error rather than false.
Shell Scripts Guide 62 of 67 Beginner
- OSRHEL 10.0
- Kernel6.12.0-55.9.1.el10_0
- dnf4.20.0
- Flatpak1.16.0
- TimeAbout 12 min
[ ] is test and is portable. [[ ]] is a bash keyword with nicer behaviour - no word splitting, && and || inside, pattern matching with =~. Both are acceptable in an answer; [ ] is what the objective names.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RHCSA-A01 | 192.168.0.31 | RHEL 10.0 | Practice node (graded) - spare /dev/sda | 2 Core | 4 GB | 50 GB + 15 GB |
This guide includes
Use this for one objective that names if, test and [ ] explicitly. This matters because the condition is an exit status rather than a boolean - and unquoted variables break the test in ways that look like logic errors.
- using the tests actually worth knowing
- seeing that the condition is an exit status rather than a true or false
- quoting so the test does not break on empty or multi-word values
Before you start
- A shell.
- The session writes and removes
~/scripts.
-
The tests worth knowing
-
Exit status is the condition
-
The quoting that stops it breaking