The tiny BASH Cheat Sheet

The tiny BASH Cheat Sheet

Update [2018-09-22@16:37]: Added some information on trap handlers and the debug “interrupt”.


The tiny BASH Cheet Sheet provides you (me) with a more or less alphabetically sorted tool-box of the expressions I most commonly use and tend to forget. I will update this cheat sheet now and then depending on more expressions I can’t remember :-)

Echo

”… echo - display a line of text …” (from man echo)

Echo new lines

text="line1\nline2\nline3\n"
echo -e "${text}"

The -e switch enables echothe interpretation of the following backslash escapes”.

Don’t echo new lines

text="line1\nline2\nline3\n"
echo "${text}"

Echo to standard error

>&2 echo "Error"

Echo to standard out and standard error

echo "Error" 1>&2;

Echo ANSI escape codes

ANSI escape codes can be used to output text in various colors:

echo -e "\033[0;31m<<<Red foreground>>>\033[0m"
echo -e "\033[0;32m<<<Green foreground>>>\033[0m"
echo -e "\033[0;34m<<<Blue foreground>>>\033[0m"
echo -e "\033[30;48;5;1m<<<Red background, black foreground>>>\033[0m"
echo -e "\033[30;48;5;2m<<<Green background, black foreground>>>\033[0m"
echo -e "\033[30;48;5;4m<<<Blue background, black foreground>>>\033[0m"

The sequence \033[0m resets the escape codes being set before. The -e switch enables echothe interpretation of the following backslash escapes”. For more effects see also bash:tip_colors_and_formatting by FLOZz' MISC.

Files

”… A computer file is a computer resource for recording data discretely in a computer storage device. …” (see Computer file - Wikipedia)

Read all lines of file

This one reads all lines of a file, including the last one not terminated with a new line:

while IFS='' read -r line || [[ -n "$line" ]]; do
  echo "${line}"
done < "/path/to/my/file.txt"

IFS stands for internal field separator and is used by the shell to determine how to do word splitting and recognize word boundaries.

If

”… At times you need to specify different courses of action to be taken in a shell script, depending on the success or failure of a command …” (see Introduction to if - Bash Guide for Beginners

IF on sub-string

Tests if a string begins with some substring:

if [[ $line = foo* ]] ; then
  echo "Starts with \"foo\" !"
fi

IF on empty variable

Tests whether a variable does not exist or is empty.

if [ -z "${var}" ] ; then
  ...
fi

IF on existing variable

Tests whether a variable exist and is not empty.

if [ -n "${var}" ] ; then
  ...
fi

IF on status code

Control flow depending of the error code of a called command:

false
if [ $? -ne 0 ]; then
    echo "Error!"
    exit 1
fi
echo "No error :-)"
true
if [ $? -ne 0 ]; then
    echo "Error!"
    exit 1
fi
echo "No error :-)"

IF on file exists

if [ ! -f /tmp/foo.txt ]; then
    echo "File not found!"
fi

Internal field separator (IFS)

IFS stands for internal field separator and is used by the shell to determine how to do word splitting and recognize word boundaries.

mystring="A:B C D"
IFS=' '; for word in $mystring; do echo "Word: $word"; done
IFS=':'; for word in $mystring; do echo "Word: $word"; done

Line segmentation

Elements by index

Get a sub-string from a string by its index given a known delimiter:

echo "1,2,3" | cut -d ',' -f 2
echo "A B C" | cut -d ' ' -f 1
echo -e "X\tY\tZ" | cut  -f 3

The cut command is used to extract sections from lines of input

Numbers

Count

Increment a value:

index="1"
index=$((index+1))

Read

”… The read utility shall read a single line from standard input. …” (from man read)

Halt till a key is pressed

You may halt the script till a key is pressed:

echo "Hit any key ..."
read -n 1 -s

Status codes

Force status code 0

true

Force status code 1

false

Shebang

Depending on the shell you want to use it looks something like this at the beginning of your script file, being introduced with a shebang (“#!”):

#!/bin/bash

Trap

”… trap [-lp] [arg] [sigspec …] … The commands in arg are to be read and executed when the shell receives signal sigspec …” (see Bash Reference Manual: Bourne Shell Builtins)

Trap signals

You may invoke your custom trap handler upon any occurrence of a control signal such as Ctrl+C, Ctrl+Y or Ctrl+Z:

trap "echo 'Bye bye!'" 1 2 3 6

For a list of signal numbers with the corresponding signals, please refer to Trap - Shell Scripting Tutorial or Signals - Bash Guide for Beginners.

Debug “interrupt”

Traps can be used for advanced functionality such as the “debug” interrupt:

#!/bin/bash
trap '
  echo "> Executing command \"$BASH_COMMAND\", press any key to continue ..."
  read -n 1 -s
' DEBUG

echo "Hello world!"
echo "Hello universe!"

Upon execution of your bash script, the trap handler is called after each invocation of your script’s commands, with the variable $BASH_COMMAND containing the bashcommand to be executed next. You may halt the script till a key is pressed (read -n 1 -s).

Variable substitution

Replace first

Replace the first occurrence of a string:

text="I am a very clever person, clever, isn't it?"
result=${text/clever/dumb}
echo "${result}"

Replace all

Replace all occurrences of a string:

text="I am a very clever person, clever, isn't it?"
result=${text//clever/dumb}
echo "${result}"

Trim leading white-spaces

shopt -s extglob
output="    This is a test"
output="${output##*( )}"
shopt -u extglob
echo "${output}"

The command shopt -s extglob enables the extended pattern matching features of the bash, whereas the command shopt -u extglob disables it again.

Trim trailing whitespaces

shopt -s extglob
output="This is a test     "
output="${output%%*( )}"
shopt -u extglob
echo "${output}"

The command shopt -s extglob enables the extended pattern matching features of the bash, whereas the command shopt -u extglob disables it again.

comments powered by Disqus