Avatar

My Shell Script cheat-sheet

← Back to list
Upd: 18.07.2021
03.06.2020
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

Read environment variables from a file and define them

The variables will be only visible to the current process.

$
if [ -f .env ]
then
export $(cat .env | xargs)
fi

Default aliases and startup settings

On every new machine I prefer having some predefined aliased and settings I am used to. So normally I write this:

👉 📃  ~/.bash_profile
$
export PS1='[\t]:\u@\W\$ '
export PATH=${PATH}:${HOME}/bin
alias ll="ls -alFh"
alias cp="cp -r"

I always keep forgetting to apply it immediately afterwards ^^

$
source ~/.bash_profile

Prompt a user

$
read -p "Running this script will sell your kidney. Proceed? " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
# dangerous operation here
fi

Create functions

$
function enterDir {
echo "Entering $1"
pushd $1 > /dev/null
}
enterDir /tmp/foo

Set the script to stop on error

$
set -e

Process arguments

$
while getopts a:b:c: flag
do
case "${flag}" in
a) OPTION_A=${OPTARG};;
b) OPTION_B=${OPTARG};;
c) OPTION_C=${OPTARG};;
*) exit 1
esac
done
echo ${OPTION_A}
echo ${OPTION_B}
echo ${OPTION_C}

This can be really powerful when combined with the default value setter.


Avatar

Sergei Gannochenko

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