RH134 Ch 1: Bash Scripts That Save You Time

A shell script is simply the commands you would type, saved in a file so they run the same way every time. Start the file with !/bin/bash so the system knows which interpreter to use, then make it executable with chmod +x. Put admin scripts in /usr/local/bin, which is already on everyone's PATH.

Arguments and variables. Inside a script $1, $2… are the arguments, $ is how many were given and $0 is the script's own name. Assign with name=value (no spaces round =) and read with "$name". Command substitution, $(command), captures output: today=$(date +%F).

Exit status and tests. Every command returns a status: 0 means success. $? holds the last one; exit 1 ends a script with a failure. test and its shorthand [ ] compare things:

- numbers: -eq -ne -gt -ge -lt -le — [ "$use" -gt 90 ] - strings: = and !=, -z (empty), -n (not empty) - files: -f (regular file), -d (directory), -x (executable)

bash if [ $ -ne 1 ]; then echo "Usage: $(basename "$0") FILE" &2 exit 1 fi for u in $(cat "$1"); do id "$u" &/dev/null || useradd "$u" done

Loops. for x in list; do …; done walks a list — words, $(cat file), {1..5} or .log. while read line; do …; done < file reads a file line by line.

grep and regular expressions. ^ anchors to the start of a line, $ to the end, . matches any character and repeats the previous item. grep ':/bin/bash

#39; /etc/passwd finds Bash users; grep -v '^' hides comments; grep -E enables +, ?, | and {n}.

Common exam mistakes - Using or < inside [ ] to compare numbers: they are redirections and quietly create files. Use -gt/-lt. - Forgetting chmod +x or the shebang line. - Leaving variables unquoted, so a blank value breaks the test ([ = foo ]). - Writing a script that fails when run twice. Check before you create.