This is a quick reference guide for creating automation scripts and using bash features to issue efficient and reliable commands.
Some entries include an example; the most straightforward ones do not.
BASIC USAGE OF VARIABLES, STRINGS, AND NUMBERS
echo [string]
[variable]=[string]
echo $[variable]
$(( [expression] ))
E.g. echo $((4*5))
Operators available:
- +
- Addition
- –
- Subtraction
- *
- Multiplication
- /
- Division
- %
- Remainder of a division
- **
- Exponentiation
$( bc -l <<< [expression] )
E.g. $( bc -l <<< 10/3 )
let [variable]=[expression]
declare -i [variable]
- MAKING A VARIABLE ACCESSIBLE TO A CHILD PROCESS (LIKE ENVIRONMENT VARIABLES)
export [variable name]=[value]
- EXECUTING A COMMAND IN THE BACKGROUND
[command] &
- LISTING BACKGROUND PROCESSES
jobs
- BRINGING A BACKGROUND PROCESS TO THE FOREGROUND
fg [job number]
- RUN A SECOND COMMAND IF THE FIRST SUCCEEDS
[command1] && [command2]
- RUN A SECOND COMMAND IF THE FIRST FAILS
[command1] || [command2]
CONDITIONAL STATEMENTS IN A SINGLE LINE
- IF
if [condition]; then [command]; fi
if [condition]; then [command1]; else [command2]; fi
if [condition1]; then [command1]; elif [condition2]; then [command2]; else [command3]; fi
- WHILE LOOP
while [condition]; do [command]; done
- UNTIL LOOP (opposite of WHILE)
until [condition]; do [command]; done
- FOR LOOP
for [variable] in [list]; do [command]; done
E.g. for name in John Mike Sarah; do echo "Hello, $name"; done
E.g. for X in {1..10}; do echo $X' >> output.txt; done
E.g. for X in $(cat list.txt); do echo $ID >> output.txt; done
for (( [initialisation]; [condition]; [increment] )); do [command]; done
E.g. for ((i=0; i<5; i++)); do echo $i; done
Note: For any of the loops above, consider using the following commands where applicable:
- “break” to exit a loop early.
- “continue” to skip the current iteration and move to the next one.
The loops above run one iteration at a time. The example below parallelizes execution, keeping a defined number of simultaneous processes running.
cat [source_file] | xargs -P [parallel] -I {} sh -c '{} >> [output_file]'
E.g. cat commands.list | xargs -P 10 -I {} sh -c '{} >> output.txt'
- CASE
case [variable] in [pattern1]) [command1];; [pattern2]) [command2];; esac
E.g. case $option in "a"|"A") echo "a or A";; "b"|"B") echo "b or B";; *) echo "Not a valid option."; esac
- SELECT
select [variable] in [list]; do [command]; done
E.g. select X in pwd uptime whoami; do $X; break; done
PROCESSING ARGUMENTS
- GETOPTS – a built-in Bash utility for parsing short options (like -a, -b, -c) and their optional arguments from the command line.
getopts [options] [variable]
E.g.
#!/bin/bash
while getopts "a:b:c" opt; do
case $opt in
a) echo "Option -a, argument: $OPTARG" ;;
b) echo "Option -b, argument: $OPTARG" ;;
c) echo "Option -c, no argument" ;;
?) echo "Usage: $0 [-a arg] [-b arg] [-c]" ;;
esac
done
- SHIFT – shifts positional parameters to the left, removing N arguments and shifting all remaining arguments down by one.
shift N
E.g.
#!/bin/bash while [ "$#" -gt 0 ]; do echo "Argument: $1" shift # Shift the arguments by one done
SIGNALS AND STATUS
- TRAP
trap [command] [signal]
E.g.
- EXIT
exit [status]
E.g.
- RETURN
return [status]
E.g.
SETTING PARAMETERS FOR THE SCRIPT EXECUTION ENVIRONMENT
- SET/UNSET to exit the script if any command returns a non-zero exit status.
set -e
set +e
- SET/UNSET to exit the script if any variable is accessed without being set.
set -u
set +u
- SET/UNSET to print each command before it is executed.
set -x
set +x
REDIRECTING OUTPUTS
- STANDARD OUTPUT (STDOUT)
[command] > [somewhere]
- STANDARD ERROR (STDERR)
[command] 2> [somewhere]
- REDIRECT STDERR INTO STDOUT
[command] > [somewhere] 2>&1
- DISCARD BOTH OUTPUTS
[command] &> /dev/null
- PIPING
[command] 2>&1 | tee [file]
- WRITING TO A FILE
[command] > [file]
SCRIPTING AND AUTOMATION
- SET THE INTERPRETER TO BASH
#!/bin/bash
- MAKE THE SCRIPT EXECUTABLE
chmod +x [script name]
- EXECUTE A SCRIPT
./[script name]
- READ USER INPUT
read [options] [variable]
Available options (all optional):
- -p
- Display a prompt message.
- -s
- Hide the entered characters (e.g. for passwords).
- -t
- Time out after a specified number of seconds.
- -d
- Set a custom delimiter instead of the default newline.
- -r
- Allow special characters such as backslash.
E.g. read -p "Enter your name: " name
E.g. read -s -p "Enter your password: " password
E.g. read -t 10 -p "Enter your input within 10 seconds: " input
E.g. read -d '|' -p "Enter your name and age separated by '|': " name age
COPY PASTE TIPS
- QUICK FORMATTING SNIPPET
BLACK=`tput setaf 0`
RED=`tput setaf 1`
GREEN=`tput setaf 2`
YELLOW=`tput setaf 3`
BLUE=`tput setaf 4`
MAGENTA=`tput setaf 5`
CYAN=`tput setaf 6`
WHITE=`tput setaf 7`
BOLD=`tput bold`
RESET=`tput sgr0`
echo -e "hello ${RED}some red text${RESET} world"
- DIALOGUE BOXES
#!/bin/bash
function box_out() {
input_char=$(echo "$@" | wc -c)
line=$(for i in `seq 0 $input_char`; do printf "─"; done)
tput bold
space=${line//─/ }
echo " ┌${line}┐"
printf ' │ ' ; echo -n "$@"; printf "%s\n" ' │';
echo " └${line}┘"
tput sgr 0
}
function box_success() {
tput bold
tput setaf 2
echo " ┌──────────┐"
echo " │ Success! │"
echo " └──────────┘"
tput sgr0
}
function box_failed() {
tput bold
tput setaf 1
echo " ┌─────────┐"
echo " │ Failed! │"
echo " └─────────┘"
tput sgr0
}
box_out "Hello there!"
box_success
box_failed
- QUICK SINGLE-LINE FORMATTED PRINTING
red() { echo -e "\033[31m [ $1 ] \033[0m" ; }
green() { echo -e "\033[32m [ $1 ] \033[0m" ; }
blue() { echo -e "\033[34m [ $1 ] \033[0m" ; }
yellow() { echo -e "\033[33m [ $1 ] \033[0m" ; }
purple() { echo -e "\033[35m [ $1 ] \033[0m" ; }
cyan() { echo -e "\033[36m [ $1 ] \033[0m" ; }
red_bold() { echo -e "\033[1;31m [ $1 ] \033[0m" ; }
green_bold() { echo -e "\033[1;32m [ $1 ] \033[0m" ; }
blue_bold() { echo -e "\033[1;34m [ $1 ] \033[0m" ; }
yellow_bold() { echo -e "\033[1;33m [ $1 ] \033[0m" ; }
purple_bold() { echo -e "\033[1;35m [ $1 ] \033[0m" ; }
cyan_bold() { echo -e "\033[1;36m [ $1 ] \033[0m" ; }
red_italic() { echo -e "\033[3;31m [ $1 ] \033[0m" ; }
green_italic() { echo -e "\033[3;32m [ $1 ] \033[0m" ; }
blue_italic() { echo -e "\033[3;34m [ $1 ] \033[0m" ; }
yellow_italic() { echo -e "\033[3;33m [ $1 ] \033[0m" ; }
purple_italic() { echo -e "\033[3;35m [ $1 ] \033[0m" ; }
cyan_italic() { echo -e "\033[3;36m [ $1 ] \033[0m" ; }
red_underline() { echo -e " \033[4;31m[ $1 ]\033[0m " ; }
green_underline() { echo -e " \033[4;32m[ $1 ]\033[0m " ; }
blue_underline() { echo -e " \033[4;34m[ $1 ]\033[0m " ; }
yellow_underline() { echo -e " \033[4;33m[ $1 ]\033[0m " ; }
purple_underline() { echo -e " \033[4;35m[ $1 ]\033[0m " ; }
cyan_underline() { echo -e " \033[4;36m[ $1 ]\033[0m " ; }
red "This is an error message." green "This is a success message." blue_bold "This is an informational message." yellow_bold "This is a warning message." purple_italic "This is a custom message." cyan_underline "This is also a custom message."
- BRACE EXPANSION
echo abc{mnp}xyz
mkdir num_{0..z}
- CHECK EXIT STATUS OF THE PREVIOUS COMMAND
echo $?
OR
case $? in 0) echo "OK";; 1) echo "Err";; *) echo "Unhandled error";; esac
- RUNNING A SCRIPT IN THE CURRENT CONTEXT OR LOADING ITS VARIABLES AND FUNCTIONS
source ./scriptName.sh argument1 argument2
OR
. ./scriptName.sh argument1 argument2
- RESTORING SESSION SETTINGS
. .profile
- HIDE THE BLINKING CURSOR DURING SCRIPT EXECUTION AND RESTORE IT AFTERWARDS
tput civis
tput cnorm