If you have spend sometime working with Linux or macOS, chances are you’ve already touched the command line. The shell is a very powerful tool—it lets you automate repetitive tasks, navigate files quickly, and even glue together complex workflows with just a few lines of text. It is a command-line interpreter — a program that takes your typed commands and passes them to the operating system to execute. There are different types of shells, for example:
Original Bourne Shell (sh)
- Bourne Again Shell (bash), the most commonly used today
C Shell (csh)
Korn Shell (ksh)
Z Shell (zsh)
In this post, I’ve collected a set of useful shell commands, snippets, and script examples that I’ve found handy in day-to-day work. These range from quick one-liners that save a few keystrokes to small scripts you can drop into your toolbox. Whether you’re just getting started with Bash or you’re looking for inspiration to make your workflow smoother, you’ll find something here to experiment with.
Variables and imports in shell scripts
# Constants SCRIPT_PATH=$(realpath "$0") SCRIPT_DIR=$(dirname "$SCRIPT_PATH") SCRIPT_NAME=$(basename "$0") NUM_SCRIPT_ARGS=$# SCRIPT_ARGS="$@" # Import definition of common functions source $SCRIPT_DIR/common_functions.sh
Shell functions
# Colors
RED="31"
GREEN="32"
ENDCOLOUR="\e[0m"
# Functions to print success, error and warning logs
function success_log {
echo -e "\e[${GREEN}m$1$ENDCOLOUR"
}
function error_log {
echo -e "\e[41mERROR: $1$ENDCOLOUR"
}
function warning_log {
echo -e "\e[${RED}mWARN: $1$ENDCOLOUR"
}
// Usage
success_log "All input files exist"
error_log "All input files don't exist"
warning_log "Output file already exists"
Control structures
# For loop
for file in $INPUT_FILES; do
echo "Input file: $file"
done
# Check if file exists
if [ ! -f $FILE ]; then
echo "File '$FILE' doesn't exist"
fi
# Check if variable is set and non-empty
if [ -z "$FTP_PASS" ]; then
echo "❌ FTP password is required."
fi
Parse script arguments
Manual parser
- Allows long options (–help, –all)
- Has maximum flexibility as it can allow multiple arguments per option
NUM_SCRIPT_ARGS=$#
while [ $NUM_SCRIPT_ARGS -gt 0 ]
do
case $1 in
-h|--help)
# Print script usage
script_usage
shift;;
-a|--all)
# Print all info
all_info
shift;;
-m|--memory)
# Print memory info
memory_info
shift;;
-s|--system)
# Print system info
system_info
shift;;
*)
echo "Invalid parameters passed to script"
# Print script usage
script_usage
esac
done
Getopts: Built-in shell utility
- No built-in support for long options (–help, –password)
- No support for optional arguments, an option either requires or doesn’t require an argument
- Each option can have maximum 1 argument
while getopts "p:s" opt; do
case $opt in
p)
# Option with argument
FTP_PASS="$OPTARG"
;;
s)
# Option without argument
SKIP_BUILD=true
;;
*)
echo "Invalid parameters passed to script"
# Print script usage
script_usage
;;
esac
done