Linux Shell Scripting Cheat Sheet

High-value Linux shell scripting reference covering variables, expansion, conditionals, loops, functions, redirection, pipelines, traps, getopts, and script debugging.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Variables and Expansion

Define shell variables, expand strings, and work safely with parameters.

Assign shell variable

Set a shell variable in the current shell.

bashLINUXshellvariablesbash
bash
name='alice'

Do not put spaces around `=` in shell variable assignments.

Export environment variable

Expose a variable to child processes.

bashLINUXshellenvironmentexport
bash
export APP_ENV=production

Used for config values consumed by child commands and scripts.

Use default value if unset

Expand parameter with a fallback.

bashLINUXshellparameter-expansiondefaults
bash
echo "${PORT:-8080}"

Useful in scripts where environment variables may be optional.

Require variable to be set

Fail fast if a variable is missing.

bashLINUXshellparameter-expansionvalidation
bash
echo "${DATABASE_URL:?DATABASE_URL is required}"

Great for scripts that should stop immediately when config is missing.

Capture command output

Assign command output to a variable.

bashLINUXshellsubstitutionvariables
bash
files=$(find . -type f | wc -l)

Use `$(...)` instead of legacy backticks.

Quote variable safely

Print variable preserving spaces.

bashLINUXshellquotingsafety
bash
printf '%s
' "$name"

Double-quote variable expansions unless you intentionally want word splitting.

Conditionals Loops and Functions

Build shell scripts that branch, loop, and encapsulate logic.

Check whether file exists

Use a shell test in an if statement.

bashLINUXshelliffiles
bash
if [[ -f /etc/app.conf ]]; then echo 'exists'; fi

Common script pattern for optional config files.

Check whether directory exists

Test for directory presence.

bashLINUXshellifdirectories
bash
if [[ -d releases ]]; then ls releases; fi

Useful for deployment and housekeeping scripts.

Loop over items

Iterate through words or filenames.

bashLINUXshellloopfor
bash
for f in *.log; do echo "$f"; done

Quote variables inside the loop body to handle spaces safely.

Read file line by line

Process lines safely using while-read.

bashLINUXshellwhileread
bash
while IFS= read -r line; do echo "$line"; done < input.txt

Preferred pattern for preserving whitespace and backslashes.

Branch with case

Match input against multiple patterns.

bashLINUXshellcasecontrol-flow
bash
case "$1" in start) echo start ;; stop) echo stop ;; *) echo usage ;; esac

Cleaner than long `if/elif` chains for command dispatch.

Define shell function

Create a reusable shell function.

bashLINUXshellfunctionbash
bash
greet() { echo "hello $1"; }

Functions help keep scripts readable and avoid repetition.

Enable strict shell behavior

Fail script on errors and unset vars.

bashLINUXshellstrict-modesafety
bash
set -euo pipefail

Widely used hardening pattern for production shell scripts.

Run cleanup on exit

Register shell cleanup logic.

bashLINUXshelltrapcleanup
bash
trap 'rm -f "$tmpfile"' EXIT

Useful for temporary files, locks, and service teardown in scripts.

Input Output and Pipelines

Redirect streams, build pipelines, and control output files.

Redirect stdout to file

Write output to a file, overwriting it.

bashLINUXshellredirectstdout
bash
echo 'hello' > greeting.txt

Use `>>` to append instead of overwrite.

Append stdout to file

Append output to an existing file.

bashLINUXshellredirectappend
bash
echo 'next line' >> app.log

Common for quick logging in scripts.

Redirect stderr to file

Send errors to a separate file.

bashLINUXshellredirectstderr
bash
command 2> errors.log

Useful when preserving errors separately from normal output.

Redirect stdout and stderr together

Capture all output in one file.

bashLINUXshellredirectstderr
bash
command > command.log 2>&1

Common logging pattern in scripts and cron jobs.

Pipe stdout to another command

Send output of one command as input to another.

bashLINUXshellpipeunix
bash
ps aux | grep nginx

Pipelines are the foundation of Unix composition.

Use process substitution

Pass command output as a pseudo-file.

bashLINUXshellprocess-substitutiondiff
bash
diff <(sort old.txt) <(sort new.txt)

Handy when a command expects file arguments but you want to compare pipeline output.

Prompt user for input

Read a value interactively.

bashLINUXshellreadinteractive
bash
read -rp 'Enter environment: ' env

Useful for operator-driven scripts and local helpers.

Print formatted output

Use printf instead of echo for predictable formatting.

bashLINUXshellprintfformat
bash
printf 'user=%s id=%s
' "$USER" "$UID"

Preferred in scripts because format control is explicit.

Script Execution and Utilities

Run scripts, parse arguments, and debug shell behavior.

Use bash shebang

Start a Bash script with an explicit interpreter.

bashLINUXshellshebangbash
bash
#!/usr/bin/env bash

Portable way to locate Bash on many systems.

Make script executable

Add execute bit to a script.

bashLINUXshellscriptchmod
bash
chmod +x deploy.sh

Then run it directly as `./deploy.sh`.

Run shell script

Execute a script from the current directory.

bashLINUXshellscriptexecution
bash
./deploy.sh

Use an explicit path so the shell does not rely on `PATH`.

Trace script execution

Print commands as they execute.

bashLINUXshelldebugbash
bash
bash -x ./deploy.sh

Very useful for debugging shell scripts and CI tasks.

Parse short options with getopts

Handle flags in shell scripts.

bashLINUXshellgetoptsarguments
bash
while getopts ':f:n:' opt; do case "$opt" in f) file="$OPTARG" ;; n) count="$OPTARG" ;; esac; done

Useful for small production scripts with predictable CLI flags.

Lint shell script

Static-analyze shell scripts for bugs.

bashLINUXshelllintshellcheck
bash
shellcheck deploy.sh

One of the highest-value tools for improving script quality.