David Härer / Cheatsheets

Bash Cheatsheet



What is the Bash strict mode?

#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

How to check if a file exists?

filepath=/tmp/example.txt
if [ -f "$filepath" ]; then
    echo "The file exists."
fi

How can I provide a default value to a variable?

# Variable bar is not set or null.
foo="${bar:-default}"
echo $foo
# default

# Variable bar is set.
bar=42
foo="${bar:-default}"
echo $foo
# 42

How can I export all variables defined in a file?

set -a
. ./.env
set +a

How can I get the filename of a filepath?

filepath="/tmp/file.txt"
filename=$(basename ${filepath})
echo ${filename}
# file.txt

How can I get the directory name of a filepath?

filepath="/tmp/file.txt"
path=$(dirname ${filepath})
echo ${path}
# /tmp

How can I get the absolute path of a filepath?

# Assume file.txt in directory /foo and working direktory in /bar.
relpath="../foo/file.txt"
abspath=$(readlink -f ${relpath})
echo ${abspath}
# /foo/file.txt

How can I get the name and extension of a filename?

filename="file.txt"

name="${filename%.*}"
echo ${name}
# file

extension="${filename##*.}"
echo ${extension}
# txt

How can I check the number of input arguments?

The $# variable holds the number of input arguments.

if [ $# -eq 0 ]; then
    echo "No arguments given."
fi

How can I only print the match of grep?

The -o option instructs grep to only print what matches the pattern.

echo "I want only THIS." | grep -o "THIS"
# THIS

What is the current time in UTC?

alias utc='date -u --iso-8601=seconds | sd T '\'' '\'' | sd '\''\+00:00'\'' '\'\'' | sd : -'

Sources