
My Shell Script cheat-sheet
← Back to list
Last updated: June 3, 2020
Image by Taylor Wilcox on Unsplash
***
Can't say I use shell scripting a lot, but when I do, I am always struggling with remembering certain useful syntax. So, this is just a reminder for the most frequently-used syntax.
LIST=$(ls -l)
📃 Copy
The code is licensed under the MIT license
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
📃 Copy
The code is licensed under the MIT license
VERSION="${1:-latest}"
📃 Copy
The code is licensed under the MIT license
FOLDER="$(pwd)"for file in ${FOLDER}/*dols -l "$file"done
📃 Copy
The code is licensed under the MIT license
basename /foo/bar/baz/wheel.txt
📃 Copy
The code is licensed under the MIT license
FILE=/etc/hostsif [[ -f "$FILE" ]]; thenecho "$FILE exists."elseecho "$FILE does not exist."fiif [[ ! -f "$FILE" ]]; thenecho "$FILE does not exist."elseecho "$FILE exists."fi
📃 Copy
The code is licensed under the MIT license
The variables will be only visible to the current process.
if [ -f .env ]thenexport $(cat .env | xargs)fi
📃 Copy
The code is licensed under the MIT license
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}/binalias ll="ls -alFh"alias cp="cp -r"
📃 Copy
The code is licensed under the MIT license
I always keep forgetting to apply it immediately afterwards ^^
source ~/.bash_profile
📃 Copy
The code is licensed under the MIT license
read -p "Running this script will sell your kidney. Proceed? " -n 1 -rechoif [[ $REPLY =~ ^[Yy]$ ]]then# dangerous operation herefi
📃 Copy
The code is licensed under the MIT license
function enterDir {echo "Entering $1"pushd $1 > /dev/null}enterDir /tmp/foo
📃 Copy
The code is licensed under the MIT license
set -e
📃 Copy
The code is licensed under the MIT license
while getopts a:b:c: flagdocase "${flag}" ina) OPTION_A=${OPTARG};;b) OPTION_B=${OPTARG};;c) OPTION_C=${OPTARG};;*) exit 1esacdoneecho ${OPTION_A}echo ${OPTION_B}echo ${OPTION_C}
📃 Copy
The code is licensed under the MIT license
This can be really powerful when combined with the default value setter.
if ! command -v <command_name> &> /dev/nullthenecho "The command was not found"exitfi
📃 Copy
The code is licensed under the MIT license
ls fooif [[ $? -ne 0 ]]; thenecho "No such directory"fi
📃 Copy
The code is licensed under the MIT license
Not exactly related to Shell scripting, but still could be useful in many cases.
@awk '{sub("fromstring","tostring")} {print}' ./.env.sample > temp.txt@mv temp.txt ./.env.test
📃 Copy
The code is licensed under the MIT license
or, better:
sed -e "s/one/another/g" -e "s/string1/string2/g" file.txt > altered_file.txt
📃 Copy
The code is licensed under the MIT license

Sergei Gannochenko
Business-focused product engineer, in ❤️ with amazing products
AI, Golang/Node, React, TypeScript, Docker/K8s, AWS/GCP, NextJS
20+ years in dev