🐚 Bash Scripting Cheat Sheet

Complete reference for Bash scripting with variables, loops, functions, conditionals, and automation techniques for system administrators and DevOps engineers

Showing 33 commands
VAR=value
Variable Operations

Assign values to variables

Syntax:

VARIABLE=value (no spaces around =)

Examples:

NAME="John Doe"

Assign string value to variable

COUNT=10

Assign numeric value

PATH=$PATH:/usr/local/bin

Append to existing variable

readonly PI=3.14159

Create read-only variable

Notes:

No spaces around = sign. Use quotes for values with spaces.

$VAR or ${VAR}
Variable Operations

Access variable values

Syntax:

$VARIABLE or ${VARIABLE}

Examples:

echo $NAME

Print variable value

echo "Hello $USER"

Use variable in string

echo ${PATH}

Explicit variable boundary

echo "${COUNT}_items"

Variable with suffix

Notes:

Use ${} for clarity and when concatenating with other text

${parameter}
Variable Operations

Advanced parameter expansion techniques

Syntax:

${parameter[:]operation}

Examples:

${VAR:-default}

Use default if VAR is empty

${VAR:=default}

Set VAR to default if empty

${VAR:?error}

Error if VAR is empty

${#VAR}

Length of variable value

${VAR%.*}

Remove shortest match from end

${VAR##*/}

Remove longest match from start

Notes:

Powerful feature for string manipulation and default values

$0, $1, $@, etc.
Variable Operations

Built-in special variables

Syntax:

Various special variable formats

Examples:

echo $0

Script name

echo $1 $2

First and second arguments

echo $#

Number of arguments

echo $@

All arguments as separate words

echo $*

All arguments as single word

echo $$

Process ID of current shell

echo $?

Exit status of last command

Notes:

Essential for script argument handling and status checking

${#string}
String Operations

Get string length

Syntax:

${#variable}

Examples:

STR="Hello World"; echo ${#STR}

Output: 11

if [ ${#PASSWORD} -lt 8 ]; then echo "Too short"; fi

Check password length

Notes:

Returns character count of the string value

${string:start:length}
String Operations

Extract substring

Syntax:

${variable:offset:length}

Examples:

STR="Hello World"; echo ${STR:0:5}

Output: Hello

STR="Hello World"; echo ${STR:6}

Output: World

STR="Hello World"; echo ${STR: -5}

Output: World (from end)

Notes:

Offset starts at 0. Negative numbers count from end (with space)

${string/pattern/replacement}
String Operations

Search and replace in strings

Syntax:

${variable/pattern/replacement}

Examples:

STR="Hello World"; echo ${STR/World/Universe}

Replace first match

STR="foo bar foo"; echo ${STR//foo/baz}

Replace all matches

STR="Hello World"; echo ${STR/#Hello/Hi}

Replace at beginning

STR="Hello World"; echo ${STR/%World/Universe}

Replace at end

Notes:

Use // for global replace, # for start, % for end matches

${string^^} / ${string,,}
String Operations

Convert string case

Syntax:

${variable^^} or ${variable,,}

Examples:

STR="Hello World"; echo ${STR^^}

Convert to uppercase: HELLO WORLD

STR="Hello World"; echo ${STR,,}

Convert to lowercase: hello world

STR="hello world"; echo ${STR^}

Capitalize first char: Hello world

Notes:

^^ = uppercase, ,, = lowercase, ^ = capitalize first

if condition
Control Structures

Conditional execution

Syntax:

if [ condition ]; then commands; fi

Examples:

if [ $USER = "root" ]; then echo "Admin user"; fi

Simple if statement

if [ -f "file.txt" ]; then echo "File exists"; else echo "File not found"; fi

If-else statement

if [ $# -eq 0 ]; then echo "No arguments"; elif [ $# -eq 1 ]; then echo "One argument"; else echo "Multiple arguments"; fi

If-elif-else chain

Notes:

Always use spaces around brackets. Use -eq, -ne, -lt, -gt for numbers

[ test ]
Control Structures

Test conditions and comparisons

Syntax:

[ expression ]

Examples:

[ $a -eq $b ]

Numbers equal

[ "$str1" = "$str2" ]

Strings equal

[ -f "file.txt" ]

File exists

[ -d "directory" ]

Directory exists

[ -r "file.txt" ]

File is readable

[ $a -gt 10 ] && [ $a -lt 20 ]

Logical AND

[ -z "$var" ]

Variable is empty

Notes:

Use quotes around variables to handle empty values safely

case variable
Control Structures

Multi-way branching

Syntax:

case $var in pattern) commands;; esac

Examples:

case $1 in start) echo "Starting...";; stop) echo "Stopping...";; *) echo "Usage: $0 {start|stop}";; esac

Simple case statement

case $file in *.txt) echo "Text file";; *.jpg|*.png) echo "Image file";; *) echo "Unknown type";; esac

Pattern matching with wildcards

Notes:

Each case ends with ;;. Use * for default case. Supports wildcards

for variable in list
Control Structures

Iterate over lists

Syntax:

for var in list; do commands; done

Examples:

for i in 1 2 3 4 5; do echo $i; done

Loop over numbers

for file in *.txt; do echo "Processing $file"; done

Loop over files

for user in $(cat users.txt); do echo "User: $user"; done

Loop over command output

for ((i=1; i<=10; i++)); do echo $i; done

C-style for loop

Notes:

Use double parentheses for arithmetic loops. Files with spaces need special handling

while condition
Control Structures

Loop while condition is true

Syntax:

while [ condition ]; do commands; done

Examples:

counter=1; while [ $counter -le 5 ]; do echo $counter; ((counter++)); done

Count from 1 to 5

while read line; do echo "Line: $line"; done < file.txt

Read file line by line

while true; do echo "Press Ctrl+C to stop"; sleep 1; done

Infinite loop

Notes:

Use 'read line' for processing files. Be careful with infinite loops

until condition
Control Structures

Loop until condition becomes true

Syntax:

until [ condition ]; do commands; done

Examples:

counter=1; until [ $counter -gt 5 ]; do echo $counter; ((counter++)); done

Loop until counter exceeds 5

until ping -c 1 google.com &> /dev/null; do echo "Waiting for internet..."; sleep 5; done

Wait for network connectivity

Notes:

Opposite of while - continues until condition is true

File test operators
File Operations

Test file properties and existence

Syntax:

[ -operator filename ]

Examples:

[ -f "file.txt" ] && echo "File exists"

Check if file exists

[ -d "directory" ] && echo "Directory exists"

Check if directory exists

[ -r "file.txt" ] && echo "File is readable"

Check if file is readable

[ -w "file.txt" ] && echo "File is writable"

Check if file is writable

[ -x "script.sh" ] && echo "File is executable"

Check if file is executable

[ -s "file.txt" ] && echo "File is not empty"

Check if file has content

[ "file1" -nt "file2" ] && echo "file1 is newer"

Compare file modification times

Notes:

Essential for robust file handling in scripts

chmod
File Operations

Change file permissions

Syntax:

chmod [permissions] filename

Examples:

chmod 755 script.sh

Make script executable by owner, readable by others

chmod +x script.sh

Add execute permission

chmod u+w,g-r file.txt

Add write for user, remove read for group

chmod a+r file.txt

Add read permission for all

Notes:

755 = rwxr-xr-x, 644 = rw-r--r--. Use +/- for relative changes

>, >>, <, |
File Operations

Redirect input/output streams

Syntax:

command [operator] file

Examples:

echo "Hello" > file.txt

Redirect output to file (overwrite)

echo "World" >> file.txt

Append output to file

sort < input.txt

Redirect file as input

command 2> error.log

Redirect stderr to file

command &> output.log

Redirect both stdout and stderr

ls | grep ".txt"

Pipe output to another command

Notes:

Use >> to append, > overwrites. 2> for errors, &> for both output and errors

command &
Process Management

Run commands in background

Syntax:

command & or bg/fg

Examples:

long_running_command &

Run command in background

jobs

List active jobs

fg %1

Bring job 1 to foreground

bg %2

Send job 2 to background

nohup command &

Run command immune to hangups

Notes:

Use Ctrl+Z to suspend, then 'bg' to background. 'nohup' survives session end

kill, killall, pkill
Process Management

Terminate processes

Syntax:

kill [signal] PID

Examples:

kill 1234

Terminate process with PID 1234

kill -9 1234

Force kill process (SIGKILL)

killall firefox

Kill all processes named firefox

pkill -f "python script.py"

Kill processes matching pattern

kill -TERM %1

Send TERM signal to job 1

Notes:

SIGTERM (15) is default, SIGKILL (9) forces termination. Use 'ps' to find PIDs

ps, top, htop
Process Management

Monitor running processes

Syntax:

ps [options] or top

Examples:

ps aux

Show all running processes

ps aux | grep python

Find Python processes

top

Interactive process monitor

pgrep -l firefox

Find process IDs by name

pidof program_name

Get PID of running program

Notes:

'ps aux' shows all processes. 'top' updates in real-time. 'q' to quit top

function name() { }
Functions

Define reusable functions

Syntax:

function_name() { commands; }

Examples:

hello() { echo "Hello, World!"; }

Simple function

greet() { echo "Hello, $1!"; }

Function with parameter

add() { echo $(($1 + $2)); }

Function returning value

backup() { local src=$1; local dst=$2; cp "$src" "$dst.bak"; }

Function with local variables

Notes:

Use 'local' for function-scope variables. $1, $2, etc. are function arguments

return [value]
Functions

Return from functions with exit status

Syntax:

return [0-255]

Examples:

check_file() { [ -f "$1" ] && return 0 || return 1; }

Return success/failure status

if check_file "test.txt"; then echo "File exists"; fi

Use function return value

get_user_count() { echo $(wc -l < /etc/passwd); }

Return value via echo

Notes:

return sets exit status (0-255). Use echo for returning values

[[ string =~ regex ]]
Pattern Matching

Match patterns with regular expressions

Syntax:

[[ string =~ pattern ]]

Examples:

[[ "hello123" =~ [0-9]+ ]] && echo "Contains numbers"

Check if string contains digits

[[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]] && echo "Valid email"

Email validation

if [[ "$filename" =~ \.txt$ ]]; then echo "Text file"; fi

Check file extension

Notes:

Use [[ ]] for regex matching. Escape special characters with backslash

*, ?, [...]
Pattern Matching

Filename globbing patterns

Syntax:

Various wildcard patterns

Examples:

ls *.txt

List all .txt files

rm temp?.log

Remove temp1.log, temp2.log, etc.

cp file[1-5].txt backup/

Copy file1.txt through file5.txt

ls [abc]*.txt

Files starting with a, b, or c

echo {1..10}

Brace expansion: 1 2 3 ... 10

cp file.txt{,.bak}

Copy file.txt to file.txt.bak

Notes:

* = any chars, ? = single char, [] = char class, {} = brace expansion

read variable
Input/Output

Read user input into variables

Syntax:

read [options] variable

Examples:

read name; echo "Hello $name"

Read user input

read -p "Enter your age: " age

Read with prompt

read -s password

Read password silently

read -t 10 response || echo "Timed out"

Read with timeout

while read line; do echo "$line"; done < file.txt

Read file line by line

Notes:

-p for prompt, -s for silent, -t for timeout, -n for character limit

printf format
Input/Output

Formatted output (more reliable than echo)

Syntax:

printf "format" arguments

Examples:

printf "Hello %s\n" "World"

Print with string formatting

printf "%d + %d = %d\n" 5 3 8

Print with number formatting

printf "%-10s %5d\n" "Name" 42

Column formatting

printf "Progress: %3d%%\n" 75

Print percentage

Notes:

More portable than echo. Use \n for newlines. %s=string, %d=integer, %f=float

set -option
Debugging

Enable shell options for debugging

Syntax:

set -[euxo]

Examples:

set -e

Exit on any command failure

set -u

Error on undefined variables

set -x

Print commands before execution

set -o pipefail

Fail if any command in pipeline fails

set -euo pipefail

Strict mode (recommended)

Notes:

Use at script start for robust error handling. set +x to disable tracing

trap command signal
Debugging

Handle signals and cleanup

Syntax:

trap 'commands' signal

Examples:

trap 'echo "Interrupted!"; exit 1' INT

Handle Ctrl+C

trap 'cleanup; exit' EXIT

Run cleanup on script exit

trap 'rm temp.txt' EXIT

Clean up temporary files

trap - INT

Reset trap to default

Notes:

Common signals: INT (Ctrl+C), TERM, EXIT. Use for cleanup operations

|| && $?
Debugging

Handle command success/failure

Syntax:

command1 && command2 || command3

Examples:

mkdir backup && echo "Directory created" || echo "Failed to create directory"

Success/failure handling

cp file.txt backup/ || { echo "Backup failed"; exit 1; }

Exit on failure

command; if [ $? -eq 0 ]; then echo "Success"; fi

Check exit status

set -e; command1; command2

Auto-exit on any failure

Notes:

&& runs if previous succeeded, || runs if previous failed. $? holds exit status

array=(elements)
Arrays

Work with arrays

Syntax:

array=(element1 element2 ...)

Examples:

fruits=(apple banana cherry)

Create array

echo ${fruits[0]}

Access first element

echo ${fruits[@]}

Print all elements

echo ${#fruits[@]}

Get array length

fruits+=(orange)

Append element

unset fruits[1]

Remove element at index 1

Notes:

Arrays are zero-indexed. Use [@] for all elements, [*] joins with IFS

grep, sed, awk
Text Processing

Process and search text

Syntax:

command [options] pattern [file]

Examples:

grep "pattern" file.txt

Search for pattern in file

grep -r "TODO" src/

Recursively search in directory

sed 's/old/new/g' file.txt

Replace text with sed

awk '{print $1}' file.txt

Print first column with awk

cut -d',' -f2 data.csv

Extract second CSV column

Notes:

grep for searching, sed for editing, awk for field processing

tar, zip, gzip
File Operations

Archive and compress files

Syntax:

tar [options] archive files

Examples:

tar -czf backup.tar.gz folder/

Create compressed archive

tar -xzf backup.tar.gz

Extract compressed archive

zip -r archive.zip folder/

Create ZIP archive

unzip archive.zip

Extract ZIP archive

gzip file.txt

Compress single file

Notes:

-c create, -x extract, -z gzip, -f file. Remember: 'tar -xzf' to extract

curl, wget, ping
Network Operations

Network operations and downloads

Syntax:

command [options] URL

Examples:

curl https://api.example.com/data

Fetch URL content

curl -o file.zip https://example.com/file.zip

Download file

wget https://example.com/file.tar.gz

Download with wget

ping -c 4 google.com

Test connectivity

curl -X POST -d '{"key":"value"}' -H 'Content-Type: application/json' https://api.example.com

POST JSON data

Notes:

curl is more versatile, wget better for downloads. ping tests connectivity

🚀 Bash Pro Tips

Essential Practices

  • set -euo pipefail - Use strict mode for robust scripts
  • "$variable" - Always quote variables to handle spaces
  • ${variable:-default} - Use parameter expansion for defaults
  • local var=value - Use local variables in functions
  • [[ ]] vs [ ] - Use [[ ]] for better test conditions
  • printf - Prefer printf over echo for portability

Debugging Techniques

  • set -x - Enable command tracing
  • bash -n script.sh - Check syntax without running
  • shellcheck - Use ShellCheck for code analysis
  • trap 'commands' DEBUG - Execute on every command
  • echo "Debug: $variable" >&2 - Debug to stderr
  • ps -ef | grep $$ - Find script process info

⚠️ Security & Best Practices

  • • Always validate user input before using in commands
  • • Use read -r to prevent backslash interpretation
  • • Avoid eval - use arrays or proper parameter expansion instead
  • • Set umask appropriately for file permissions
  • • Use absolute paths in scripts or set PATH explicitly
  • • Handle signals with trap for proper cleanup

📚 Advanced Learning

Master Bash scripting with these advanced concepts and tools:

🔧 Process Substitution

Use <(command) and >(command) for advanced I/O

📋 Here Documents

Master <<EOF for multi-line input and templating

🔀 Coprocesses

Use coproc for bidirectional communication