Bash scripts: variables, conditions, loops
Sign in to read this lesson
If you are typing the same commands for the third time, it is time for a script. RHCSA also has small scripting tasks — for example, "read users from a file and create them" or "give a different result depending on a parameter". In this lesson we learn variables, parameters, exit codes, if/case conditions, for/while loops and the rules for writing safe scripts.
What you will learn
- A script starts with
#!/bin/bashand becomes executable withchmod +x;bash -n script.shchecks the syntax,bash -xshows step-by-step execution. - A variable:
NAME="value"(no spaces around the equals sign), used as"$NAME"— always quoted; a command's output is$(command). - Parameters:
$1,$2,$#(count),$@(all); the exit code$?— 0 success, anything else an error;exit 1. - Conditions:
if [[ -f "$F" ]]; then ... elif ...; else ...; fi; many options —case. - Loops:
for u in $(cat list); do ...; done,while read -r line; do ...; done < file.
The lesson has 5 key points, an explanation and 5 questions. It opens with a package.