RHCSA study materials
RHCSA study resources

RHCSA: Create simple shell scripts

RHCSA · Work through your exam, one topic at a time.

All guide sections

Create simple shell scripts

Structure

Start every script with #!/bin/bash. Assign variables with no spaces around =, expand with "$var" (quoted), and capture command output with $(command). Positional parameters are $1..$9, $# (count), $@ (all arguments as separate words), and $? (last exit status). Arithmetic uses $(( )) or let. Return a status with exit N.

Logic

if [ "$x" -eq 5 ]; then ... elif ...; fi needs spaces inside the brackets and a matching fi. Numeric tests: -eq -ne -lt -le -gt -ge. String tests: =, !=, -z (empty), -n (non-empty). File tests: -f -d -e -r -w -x -s. [[ ]] adds pattern matching and safer quoting. Loops look like for f in *.txt; do ...; done and while read -r line; do ...; done < file; case handles menus; read -p prompts.

Habits

set -e exits on error, set -u errors on unset variables, and bash -x script traces execution for debugging. Make the file executable with chmod +x or invoke it as bash script. Always redirect or append output to a log, and never run rm -rf $dir on an unquoted variable that might be empty.

Traps: using -eq on non-numeric text produces 'integer expression expected'; unquoted [ $var = yes ] breaks when $var is empty; forgetting fi or done is a syntax error. A script without a shebang and execute bit fails under ./script.

Rule of thumb: numbers get -eq, strings get =, and every expansion is quoted.

Worked example:

for u in $(cut -d: -f1 /etc/passwd); do
  [ "$u" = root ] && continue
  echo "user: $u"
done