guest@linuxthings: ~/guides/scripting.md

guest@linuxthings:~/guides$ man scripting

Shell Scripting

Combine commands into a file to automate tasks. Files usually end in .sh and need executable permissions.

Example Script

#!/bin/bash
# Basic script structure

NAME="World"
echo "Hello, $NAME!"

if [ -f "/etc/passwd" ]; then
  echo "Password file exists."
fi

# Loop through files
for file in *.txt; do
  echo "Found text file: $file"
done

Running Scripts

chmod +x script.sh
./script.sh                # Run from the current directory
bash script.sh             # Run without making it executable
source script.sh           # Run inside the current shell (same as: . script.sh)
bash -n script.sh          # Check syntax without running
bash -x script.sh          # Trace each command as it runs (debugging)

The #!/bin/bash line must be the very first line. Use source when the script should change your current shell, for example by setting variables or changing directory.

Variables and Quoting

name="Ada"                 # No spaces around =
echo "Hello, $name"        # Always quote variables
echo "${name}s"            # Braces separate the name from following text
today=$(date +%F)          # Store a command's output
readonly PI=3.14           # A constant
echo "${missing:-default}" # Use a default if the variable is unset or empty

Quote variables ("$file") so values containing spaces stay as one argument. An unquoted $file holding My Document becomes two arguments.

Arguments and Exit Codes

Variable

Meaning

$0

Name of the script

$1, $2 ...

Positional arguments

$#

Number of arguments

"$@"

All arguments, each kept separate

$?

Exit code of the last command (0 = success)

$$

PID of the script

if [ $# -lt 1 ]; then
  echo "Usage: $0 filename" >&2   # Errors go to stderr
  exit 1                          # Non-zero means failure
fi

for arg in "$@"; do
  echo "Argument: $arg"
done

Tests

Test

True when

-f file / -d dir

It exists and is a regular file / directory

-e path

Anything exists at that path

-r / -w / -x file

It is readable / writable / executable

-s file

It exists and is not empty

-z "$s" / -n "$s"

String is empty / not empty

"$a" = "$b" / !=

Strings are equal / different

$a -eq $b

Integers are equal (also -ne -lt -le -gt -ge)

[ ... ] needs spaces inside the brackets. Bash's [[ ... ]] is more forgiving and adds pattern matching, such as [[ $file == *.txt ]].

Conditionals

if [[ $count -gt 10 ]]; then
  echo "Big"
elif [[ $count -gt 5 ]]; then
  echo "Medium"
else
  echo "Small"
fi

if grep -q "error" log.txt; then   # Any command can be the test
  echo "Errors found"
fi

case "$1" in
  start) echo "Starting" ;;
  stop)  echo "Stopping" ;;
  *)     echo "Usage: $0 {start|stop}"; exit 1 ;;
esac

Loops

for i in {1..5}; do echo "Pass $i"; done

for host in web1 web2 db1; do
  ping -c1 "$host" > /dev/null && echo "$host is up"
done

while read -r line; do           # Read a file line by line
  echo "Line: $line"
done < input.txt

count=0
while [ $count -lt 3 ]; do
  count=$((count + 1))
done

Arithmetic

echo $(( 5 + 3 * 2 ))      # 11
x=7; echo $(( x % 3 ))     # Remainder: 1
(( x++ ))                  # Increment
echo "scale=2; 10/3" | bc  # Decimals need bc

Functions

greet() {
  local who="$1"           # local keeps the variable inside the function
  echo "Hello, $who"
}

greet "Linux"

Reading Input and Here Documents

read -p "Your name: " name
read -s -p "Password: " pass; echo   # -s hides typing

cat <<EOF > config.txt
user=$USER
created=$(date)
EOF

Safer Scripts

set -u                     # Treat unset variables as errors
set -e                     # Exit on the first failing command
set -o pipefail            # A pipeline fails if any part fails

set -e has surprising exceptions (for example, a command in an if test or an arithmetic result of zero), so still check important commands explicitly. Run shellcheck script.sh to catch common mistakes such as missing quotes.

guest@linuxthings:~/guides$