Skip to content

Bash cheatsheet

Basics

Variables

Define variable

name="John"

Use the variable

echo $name
echo "$name"
echo "${name}!"

Substitution/slicing

  • echo "${name/J/j}" “john” (substitution)
  • echo "${name:0:2}" “Jo” (slicing)
  • echo "${name::2}" “Jo” (slicing)
  • echo "${name::-1}" “Joh” (slicing)
  • echo "${name:(-1)}" “n” (slicing from right)
  • echo "${name:(-2):1}" “h” (slicing from right)

Change case

  • echo "${str,}" lowercase 1st letter
  • echo "${str,,}" all lowercase
  • echo "${str^}" uppercase 1st letter
  • echo "${str^^}" all uppercase

Default values

  • ${foo:-val} $foo, or val if unset (or null)
  • ${foo:=val} Set $foo to val if unset (or null)
  • ${foo:+val} val if $foo is set (and not null)
  • ${foo:?message} Show error message and exit if $foo is unset (or null)

Shell execution

echo "Current directory $(pwd)"
echo "Current directory `pwd`" 

Comments

Single line

# Single line comment

Multi line

: '
This is a
multi line
comment
'

Special variables

  • $? Exit status of last task
  • $! PID of last background task
  • $$ PID of shell
  • $0 Filename of the shell script
  • $_ Last argument of the previous command

Loops

For loop

for i in {1..10}; do
  echo $i;
done
for i in $(seq 1 10); do
  echo $i;
done

C-like version

for ((i = 0 ; i < 100 ; i++)); do
  echo "$i"
done

While

while read -r line; do
  echo "$line"
done <file.txt

Infinite loop

while true; do
  ···
done

Functions

Define function

function hello {
    echo "hello world"
}
hello() {
    echo "hello world"
}

Arguments

  • $# Number of arguments
  • $* All arguments (as a single word)
  • $@ All arguments (as separate strings)
  • $1, $2, $3 First, second, third argument
  • $_ Last argument of the previous command

Conditions

File

  • [[ -e FILE ]] Exists
  • [[ -r FILE ]] Readable
  • [[ -h FILE ]] Symlink
  • [[ -d FILE ]] Directory
  • [[ -w FILE ]] Writable
  • [[ -s FILE ]] Size is > 0 bytes
  • [[ -f FILE ]] File
  • [[ -x FILE ]] Executable
  • [[ FILE1 -ef FILE2 ]] Same files

Example

if [[ -e "file.txt" ]]; then
  echo "File exists"
fi

String

  • [[ -z STRING ]] Empty
  • [[ -n STRING ]] Not empty
  • [[ STRING1 == STRING2 ]] Equal
  • [[ STRING1 != STRING2 ]] Not Equal

Example

if [[ -z "$string" ]]; then
  echo "String is empty"
else
  echo "String is not empty"
fi

Number

  • [[ NUM1 -eq NUM2 ]] Equal
  • [[ NUM1 -ne NUM2 ]] Not equal
  • [[ NUM1 -lt NUM2 ]] Less than
  • [[ NUM1 -le NUM2 ]] Less than or equal
  • [[ NUM1 -gt NUM2 ]] Greater than
  • [[ NUM1 -ge NUM2 ]] Greater than or equal

Example

if [[ $n -gt $n2  ]]; then
  ...
elif [[ $n -eq $n2 ]]; then
  ...
else
  ...
fi

Logical operators

  • [[ ! EXPR ]] Not
  • [[ X && Y ]] And
  • [[ X || Y ]] Or
if [[ $x && $y ]]; then
  ...
fi

Switch/Case

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

Redirections

  • ./program > output.txt stdout to file
  • ./program >> output.txt append stdout to file
  • ./program 2> error.log stderr to file
  • ./program 2>&1 stderr to stdout
  • ./program 2>/dev/null stderr to /dev/null
  • ./program >output.txt 2>&1 stdout and stderr to file, equivalent to &>
  • ./program &>/dev/null stdout and stderr to /dev/null
  • ./program < input.txt stdin from input.txt
  • ./program | grep "file" stdout to another programs’ stdin

Heredoc

cat <<END
...
END

History

Show history

history

Clear history

history -c

Expansions

  • !$ Expand last parameter of most recent command
  • !* Expand all parameters of most recent command
  • !-n Expand nth most recent command
  • !n Expand nth command in history
  • !<command> Expand most recent invocation of command <command>

Temporarily disable bash history

Disable history file until end of session:

unset HISTFILE

Disable/enable using set in one session:

set +o history
# commands here won't be saved
set -o history

Set environment variables:

export HISTSIZE=0
export SAVEHIST=0

Show Date and Time

Display time and date before each command in history

HISTTIMEFORMAT="%d-%m-%y %r " history
  • %d – Day
  • %m – Month
  • %y – Year
  • %T / %r – Time in 24/12 hours format

To set this permanently, add HISTTIMEFORMAT variable definition to your .bashrc file

export HISTTIMEFORMAT="%d-%m-%y %r "