My Shell Script cheat-sheet

Photo by Taylor Wilcox on Unsplash
Refill!

Can't say I use shell scripting a lot, but when I do, I always struggling with remembering certain useful syntax. So, this is just a reminder for the most frequently-used syntax.

Save command output to a variable

$
LIST=$(ls -l)

Get the basename of the full path to the script file

$
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Assign the default value to a variable

$
VERSION="${1:-latest}"

Execute a command for each file in the folder

$
FOLDER="$(pwd)"
for file in ${FOLDER}/*
do
ls -l "$file"
done

Get basename of a path

$
basename /foo/bar/baz/wheel.txt

Check if file exists

$
FILE=/etc/hosts
if [[ -f "$FILE" ]]; then
echo "$FILE exists."
else
echo "$FILE does not exist."
fi
if [[ ! -f "$FILE" ]]; then
echo "$FILE does not exist."
else
echo "$FILE exists."
fi

Sergei Gannochenko

Business-oriented fullstack engineer, in ❤️ with Tech.
JS / JS stack: React, Node, Docker, AWS.
15+ years in dev.