Duncan Wither

Home Notes Github LinkedIn

Scripting Cheat Sheet

Written: 05-Mar-2022

Bash

Here’s someone else’s cheatsheet

Hashbang

#!/bin/bash

for Loop

To loop over files in a directory:

for f in $FILES
do
    # Do something here
    echo "Reading filename: $f"
done

To loop over the lines of a file use (useful if there are spaces in a list of filenames):

while IFS= read -r line
do
    # Doing something on each line
    echo "Text read from file: $line"
done < my_filename.txt

if Statement

if [ expression ]
then
   Statement(s) for true
else
   Statement(s) for false
fi

Check two numbers are equal

[ "$a" -eq "$b" ]

Check two strings are equal

[ "$str1" = "$str2" ]

File Names w/ Spaces

IFS=$'\n'

Or liberally apply quotes.

Function arguments

### User Input

read -r -p "Are you sure? [y/N] " response
case "$response" in
    [yY][eE][sS]|[yY])
        do_something
        ;;
    *)
        do_something_else
        ;;
esac

Check Path to directory Exists

[ -d "/path/to/dir" ] && echo "Directory /path/to/dir exists."
 
## OR ##
[ ! -d "/path/to/dir" ] && echo "Directory /path/to/dir DOES NOT exists."

For files use -f instead!