VOCABULARY
Bash Scripting Vocabulary & Glossary
Section titled “Bash Scripting Vocabulary & Glossary”Comprehensive Glossary of Bash Terms, Concepts, and Commands
Section titled “Comprehensive Glossary of Bash Terms, Concepts, and Commands”This vocabulary provides detailed definitions of bash scripting terminology, organized alphabetically for easy reference. Each term includes practical examples relevant to DevOps, SRE, and SysAdmin roles on Arch Linux.
Absolute Path
Section titled “Absolute Path”A path that starts from the root directory (/). Absolute paths are unambiguous and work regardless of current working directory. Essential for scripts that need predictable file access.
# Absolute path examples/etc/nginx/nginx.conf/usr/bin/bash/var/log/syslog/home/username/projects
# Using in scriptsCONFIG_FILE="/etc/myapp/config.conf"if [[ -f "$CONFIG_FILE" ]]; then source "$CONFIG_FILE"fi
# Relative to script locationSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"CONFIG_FILE="${SCRIPT_DIR}/config/app.conf"A user-defined shortcut for a command or command sequence. Aliases are commonly used in DevOps for frequently used commands.
# Define aliasalias ll='ls -la'alias k='kubectl'alias dps='docker ps'alias kubectx='kubectl config use-context'
# Alias with parameters (needs function)alias logs='kubectl logs -f'alias kpod='kubectl get pods -o wide'
# Make persistent in ~/.bashrcecho "alias ll='ls -la'" >> ~/.bashrc
# Reload bashrcsource ~/.bashrc
# List all aliasesalias
# Remove aliasunalias llAnchors (Regex)
Section titled “Anchors (Regex)”Special characters that match positions in a string rather than characters. Essential for pattern matching in log analysis and validation.
# ^ - Start of string/lineecho "testing" | grep '^test' # Matchesecho "atesting" | grep '^test' # No match
# $ - End of string/lineecho "testing" | grep 'ing$' # Matchesecho "testingx" | grep 'ing$' # No match
# Word boundariesecho "hello world" | grep '\bworld\b' # Matches whole word
# Real-world examples# Validate IP addressip="192.168.1.1"if [[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo "Valid IP"fi
# Validate emailemail="user@example.com"if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then echo "Valid email"fiArithmetic Expansion
Section titled “Arithmetic Expansion”The process of evaluating arithmetic expressions using $(( )) syntax. Bash only supports integer arithmetic. Critical for numeric operations in scripts.
# Basic operationsresult=$((5 + 3)) # result = 8result=$((10 - 3)) # result = 7result=$((4 * 5)) # result = 20result=$((10 / 3)) # result = 3 (integer division)result=$((10 % 3)) # result = 1 (modulo)
# Compound operationsresult=$(( (5 + 3) * 2)) # result = 16result=$(( 10 ** 2 )) # result = 100 (exponentiation, bash 4+)
# Variablesa=10b=3sum=$((a + b)) # 13product=$((a * b)) # 30quotient=$((a / b)) # 3remainder=$((a % b)) # 1
# Increment/decrement((count++)) # Post-increment((++count)) # Pre-increment((count--)) # Post-decrement((--count)) # Pre-decrement
# Compound assignment((count += 5)) # count = count + 5((count -= 3)) # count = count - 3((count *= 2)) # count = count * 2
# Using with bc for floating pointresult=$(echo "scale=2; 10 / 3" | bc) # 3.33result=$(echo "sqrt(2)" | bc -l) # 1.41A variable that can hold multiple values. Bash supports indexed arrays (numeric keys) and associative arrays (string keys). Essential for handling lists in automation scripts.
# Create indexed arrayfruits=(apple banana cherry orange)
# Access elementsecho "${fruits[0]}" # apple (first element)echo "${fruits[-1]}" # orange (last element)echo "${fruits[@]}" # all elementsecho "${#fruits[@]}" # array length (4)
# Slice arrayecho "${fruits[@]:1:2}" # banana cherry (from index 1, length 2)
# Append elementsfruits+=(grape mango)fruits=( "${fruits[@]}" "watermelon" )
# Modify elementfruits[0]="APPLE"
# Delete elementunset fruits[2] # Remove third element
# Array from command outputfiles=(*.log) # All .log files in current dirlines=($(cat file.txt)) # Split by IFS
# Associative array (requires bash 4+)declare -A user_infouser_info[name]="john"user_info[role]="admin"user_info[email]="john@example.com"
# Accessecho "${user_info[name]}" # johnecho "${!user_info[@]}" # name role email (keys)echo "${user_info[@]}" # john admin john@example.com (values)
# Iteratefor fruit in "${fruits[@]}"; do echo "Fruit: $fruit"done
# Real-world: Server listservers=(web-01 web-02 web-03 db-01 cache-01)for server in "${servers[@]}"; do echo "Checking $server..." ssh "$server" "uptime"doneBackground Process
Section titled “Background Process”A process that runs without controlling the terminal. Started with & operator. Essential for running multiple tasks in parallel in DevOps scripts.
# Run in background./backup.sh &./deploy.sh &./monitor.sh &
# Store PID for later control./long_running_task.sh &PID=$!echo "Started task with PID: $PID"
# Wait for background processwait $PIDecho "Task completed"
# Wait for multiple processes./task1.sh &PID1=$!./task2.sh &PID2=$!wait $PID1 $PID2echo "All tasks completed"
# Background with output redirection./backup.sh > /var/log/backup.log 2>&1 &
# Check if process is runningif ps -p $PID > /dev/null 2>&1; then echo "Process is running"fi
# Kill background processkill $PID
# List background jobsjobsBash Built-in Commands
Section titled “Bash Built-in Commands”Commands that are part of the shell itself. These execute faster than external commands as they don’t require spawning a new process.
| Command | Description | DevOps Use Case |
|---|---|---|
echo | Print to stdout | Logging, output |
printf | Formatted output | CSV generation, reports |
read | Read input | Interactive scripts |
cd | Change directory | Automation scripts |
pwd | Print working directory | Path verification |
export | Set environment | CI/CD pipelines |
source | Execute file | Loading configs |
alias | Command shortcut | Custom shortcuts |
local | Declare local variable | Function scope |
declare | Declare variable/array | Type definitions |
typeset | Declare variable | Function scope (legacy) |
readonly | Mark as read-only | Constants |
shift | Shift positional params | Argument parsing |
getopts | Parse options | CLI argument parsing |
eval | Evaluate string as command | Dynamic commands |
exec | Replace shell process | Script execution |
trap | Signal handler | Cleanup, signals |
test | Conditional expression | Conditionals |
true | Return success | Infinite loops |
false | Return failure | Exit with error |
set | Set shell options | Debugging, options |
shopt | Shell options | Extended features |
Brace Expansion
Section titled “Brace Expansion”A bash feature that generates strings from patterns. It occurs before any other expansion.
# Sequence generationecho {1..5} # 1 2 3 4 5echo {01..10} # 01 02 03 04 05 06 07 08 09 10echo {a..f} # a b c d e fecho {A..Z} # A B C D ... Z
# Letter sequencesecho {a,z,m} # a z m
# File combinationstouch file{1,2,3}.txt # file1.txt file2.txt file3.txtmkdir -p project/{src,bin,tests,docs,config}
# Complex patternsecho {log,error,access}.{txt,log}# log.txt log.log error.txt error.log access.txt access.log
# Nested bracesecho {{A,B},{a,b}}# A a B b
# Real-world examples# Backup multiple filescp file{,.backup}
# Create multiple directoriesmkdir -p app/{config,controllers,models,views,public}
# Note: Brace expansion happens first - variables won't work insideNAME="test"echo {$NAME.txt} # Literal: {test.txt}Case Statement
Section titled “Case Statement”A multi-way branch construct similar to switch-case in other languages. Used for menu-driven scripts and option parsing.
# Basic syntaxcase $variable in pattern1) command1 command2 ;; pattern2) command3 ;; *) default_command ;;esac
# Real-world example: Service managementcase $1 in start) echo "Starting service..." systemctl start myapp echo "Service started" ;; stop) echo "Stopping service..." systemctl stop myapp echo "Service stopped" ;; restart) echo "Restarting service..." $0 stop sleep 2 $0 start ;; status) systemctl status myapp ;; *) echo "Usage: $0 {start|stop|restart|status}" exit 1 ;;esac
# Multiple patternscase $extension in txt|log) echo "Text file" ;; jpg|png|gif) echo "Image file" ;; sh|bash) echo "Shell script" ;; *) echo "Unknown type" ;;esacCharacter Class
Section titled “Character Class”A set of characters enclosed in square brackets used in pattern matching.
# Basic character classes[abc] # a, b, or c[^abc] # NOT a, b, or c (negation)[a-z] # any lowercase letter[A-Z] # any uppercase letter[0-9] # any digit
# POSIX character classes[[:alpha:]] # alphabetic characters[[:digit:]] # digits [0-9][[:lower:]] # lowercase letters[[:upper:]] # uppercase letters[[:alnum:]] # alphanumeric[[:space:]] # whitespace[[:punct:]] # punctuation[[:print:]] # printable characters
# Examples[[ "hello" =~ ^[a-z]+$ ]] # true[[ "HELLO" =~ ^[A-Z]+$ ]] # true[[ "hello123" =~ ^[[:alnum:]]+$ ]] # true
# Real-world: Validate filenamefilename="report_2024.pdf"if [[ "$filename" =~ ^[[:alnum:]_.-]+\.(pdf|docx?|xlsx?)$ ]]; then echo "Valid filename"fiCommand Substitution
Section titled “Command Substitution”Replacing a command with its output. Critical for capturing command results in variables.
# Modern syntax (preferred)current_date=$(date +%Y-%m-%d)files=$(ls -1 /var/log/*.log)hostname=$(hostname)
# Legacy syntax (backticks - avoid)current_date=`date +%Y-%m-%d`
# Nested command substitutionouter=$(echo $(inner_function))outer=$(compute_value "$(get_config)")
# Preserve newlinesoutput=$(cat large_file.txt)
# Command substitution in variable assignmentBACKUP_DIR="/backup/$(date +%Y%m%d)"IP_ADDRESS=$(curl -s ifconfig.me)
# Exit status with command substitutionoutput=$(command) || echo "Command failed"# Better approach:if output=$(command 2>&1); then echo "Success: $output"else echo "Failed: $output"fiCompound Command
Section titled “Compound Command”A shell command that groups multiple commands together.
# Subshell - runs in child process( cd /tmp pwd # /tmp, but original dir unchanged)
# Current shell group{ cd /tmp pwd # /tmp, stays in current shell}
# Pipeline - multiple commandscmd1 | cmd2 | cmd3
# Arithmetic evaluation((x = 5 + 3))
# Array evaluation((arr=(1 2 3)))Conditional Expression
Section titled “Conditional Expression”An expression that evaluates to true or false, used in [[ ]] or [ ].
# File tests[[ -e file ]] # File exists[[ -f file ]] # Regular file exists[[ -d file ]] # Directory exists[[ -L file ]] # Symbolic link exists[[ -r file ]] # File is readable[[ -w file ]] # File is writable[[ -x file ]] # File is executable[[ -s file ]] # File exists and is not empty
# String tests[[ -z string ]] # String is empty[[ -n string ]] # String is not empty[[ string1 == string2 ]] # Equal[[ string1 != string2 ]] # Not equal[[ string =~ regex ]] # Matches regex
# Numeric tests[[ num1 -eq num2 ]] # Equal[[ num1 -ne num2 ]] # Not equal[[ num1 -lt num2 ]] # Less than[[ num1 -gt num2 ]] # Greater than
# Combined conditions[[ -f file ]] && echo "File exists"[[ -d dir ]] || echo "Directory not found"
# Real-world examples# Check if service is runningif systemctl is-active --quiet nginx; then echo "Nginx is running"fiCoprocess
Section titled “Coprocess”A subprocess running in parallel with the shell, with bidirectional communication. Advanced feature for interactive commands.
# Start bc as coprocesscoproc BC { bc -l; }
# Send input to coprocessecho "sqrt(2)" >&${BC[1]}
# Read output from coprocessread -r result <&${BC[0]}echo "Result: $result"
# Using named coprocesscoproc BC { bc -l 2>&1; }
# Real-world: Database interactioncoproc DB { sqlite3 mydb.db; }
echo "CREATE TABLE test(id INTEGER);" >&${DB[1]}echo "INSERT INTO test VALUES(1);" >&${DB[1]}echo "SELECT * FROM test;" >&${DB[1]}
# Clean upkill $DB_PID 2>/dev/nullDebugging Mode
Section titled “Debugging Mode”Running Bash with debug options enabled. Essential for troubleshooting scripts.
# Trace execution (shows commands with expansion)bash -x script.sh
# Verbose (shows input lines)bash -v script.sh
# Check syntax without executionbash -n script.sh
# Combine optionsbash -xv script.sh
# Debug specific sectionset -x # Enable tracingcommands_to_debugset +x # Disable tracing
# ERR tracing (bash 4+)set -e # Exit on errorset -o errtrace # ERR trap inherited
# DEBUG traptrap 'echo "Executing: $BASH_COMMAND"' DEBUG
# EXIT trap (cleanup)trap 'echo "Cleaning up..."; rm -f /tmp/temp' EXIT
# Use in script#!/bin/bashset -x # Start debuggingset -e # Exit on errorset -u # Exit on undefined variableset -o pipefail # Pipeline fails if any command fails
# Production script template#!/usr/bin/env bashset -euo pipefailtrap 'err=$?; echo "Error at line $LINENO"; exit $err' ERRDerived Shell (dash)
Section titled “Derived Shell (dash)”A POSIX-compliant shell used as /bin/sh on many systems. Scripts using POSIX features are more portable.
# Check default shellls -l /bin/sh
# On Debian/Ubuntu: /bin/sh -> dash# On Arch Linux: /bin/sh -> bash
# For portability, avoid bash-specific features# ✓ [ "$var" = "value" ] (not ==)# ✓ ${var:-default} (parameter expansion)# ✗ [[ ]] (bash extension)# ✗ (( )) (bash arithmetic)
# Check script compatibilityshellcheck -s sh script.shEnvironment Variable
Section titled “Environment Variable”A variable that affects the behavior of processes and other programs. Critical in DevOps for configuration.
# Set environment variableexport APP_ENV="production"export DATABASE_URL="postgresql://localhost:5432/mydb"export PATH="/usr/local/bin:$PATH"
# Permanently (in ~/.bashrc)echo 'export APP_ENV="production"' >> ~/.bashrc
# Unsetunset APP_ENV
# View allenvprintenvprintenv HOME
# One-time exportAPP_ENV=production ./script.sh
# In scriptsif [[ "$APP_ENV" == "production" ]]; then echo "Running in production mode"fiEscape Sequence
Section titled “Escape Sequence”A sequence of characters that represents a special character.
# Common escape sequences\n # Newline\t # Tab\r # Carriage return\\ # Backslash\" # Double quote\' # Single quote\a # Alert (bell)\b # Backspace
# Examplesecho -e "Line1\nLine2" # Two linesecho -e "Col1\tCol2" # Tab-separated
# In printfprintf "Name:\t%s\nAge:\t%d\n" "John" 30Exit Status
Section titled “Exit Status”A numeric value returned by a command indicating success (0) or failure (non-zero). Foundation of error handling.
# Check exit statusls /etc/passwdecho $? # 0 (success)
ls /nonexistentecho $? # 1 or 2 (failure)
# Using exit status in conditionalsif grep -q "pattern" file.txt; then echo "Pattern found"fi
# Capture exit statusgrep "pattern" file.txtstatus=$?
# Common exit codes# 0 - Success# 1 - General error# 2 - Misuse of shell command# 126 - Command not executable# 127 - Command not found# 130 - Script terminated by Ctrl+C (128 + 2)# 143 - Script terminated by SIGTERM (128 + 15)
# Explicit exitexit 0 # Successexit 1 # General errorexit 2 # Usage errorA unit of data separated by a delimiter (typically whitespace). Important for text processing.
# Default IFS splits on whitespaceline="one two three"echo $line | awk '{print $1}' # oneecho $line | awk '{print $3}' # three
# Custom IFSline="one,two,three"IFS=',' read -ra fields <<< "$line"echo "${fields[0]}" # one
# Using cutecho "col1 col2 col3" | cut -d' ' -f1 # col1
# CSV processingwhile IFS=',' read -r name email role; do echo "User: $name, Email: $email"done < users.csvFile Descriptor
Section titled “File Descriptor”An integer that represents an open file for a process. Each process has file descriptors 0, 1, 2 by default.
| Descriptor | Name | Description |
|---|---|---|
| 0 | stdin | Standard input (keyboard) |
| 1 | stdout | Standard output (terminal) |
| 2 | stderr | Standard error (terminal) |
| 3-9 | custom | Available for custom use |
# Redirect stdout to fileecho "hello" > output.txtecho "world" >> output.txt
# Redirect stderr to filegrep "pattern" file 2> errors.txt
# Redirect bothcommand > output.txt 2>&1command &> all.txt
# Redirect to /dev/nullcommand 2> /dev/nullcommand > /dev/null 2>&1
# Custom file descriptorsexec 3> file.txtecho "Line 1" >&3exec 3>&-
# Process substitutiondiff <(ls dir1) <(ls dir2)Function
Section titled “Function”A reusable code block that performs a specific task. Essential for code organization.
# Function definition (two syntaxes)function backup_files { local source="$1" local dest="$2"
echo "Backing up $source to $dest" tar -czf "$dest" "$source"
return $?}
# POSIX compatiblebackup_files() { local source="$1" local dest="$2"
echo "Backing up $source to $dest" tar -czf "$dest" "$source"
return $?}
# Call functionbackup_files "/home" "/backup/home.tar.gz"
# Function with return value (via echo)get_date() { date +%Y-%m-%d}current_date=$(get_date)
# Function with output variable (nameref)get_square() { local -n result="$1" local num="$2" result=$((num * num))}get_square sq 5echo "Square: $sq"Globbing
Section titled “Globbing”Pattern matching for filename expansion (wildcards). Performed after other expansions.
# Basic wildcards* # Any characters (except /)? # Single character[abc] # Character class[!abc] # Negated class
# Match all .txt filesls *.txt
# Match files with single characterls file?.log # file1.log, file2.log
# Match specific charactersls file[123].log # file1.log, file2.log, file3.log
# Extended globbing (enable with shopt)shopt -s extglobls !(*.log) # All files except .logls +(www|ftp)/*.logHash Table / Associative Array
Section titled “Hash Table / Associative Array”An associative array implementation in Bash (called associative arrays). Requires bash 4+.
# Declare associative arraydeclare -A config
# Add key-value pairsconfig[host]="localhost"config[port]="8080"config[database]="mydb"
# Access valuesecho "${config[host]}" # localhost
# List all keysecho "${!config[@]}" # host port database
# Iteratefor key in "${!config[@]}"; do echo "$key = ${config[$key]}"done
# Real-world: Server inventorydeclare -A server_ipsserver_ips[web-01]="192.168.1.10"server_ips[db-01]="192.168.1.20"
get_ip() { local server="$1" echo "${server_ips[$server]:-unknown}"}Here Document
Section titled “Here Document”A way to provide input to a command using inline text. Excellent for multi-line input.
# Basic here documentcat << EOFThis is line 1This is line 2Variable: $VARSubshell: $(date)EOF
# Without variable expansion (quoted delimiter)cat << 'EOF'This is literal: $VARThis won't expand either: $(date)EOF
# Use in scripts: Generate config filecat > /etc/myapp.conf <<-EOF# My Application Configurationhost = ${DB_HOST:-localhost}port = ${DB_PORT:-5432}debug = falseEOF
# Use with commandsmysql -u root -p <<EOFCREATE DATABASE IF NOT EXISTS myapp;USE myapp;SELECT * FROM users;EOFHere String
Section titled “Here String”Input redirection using a string instead of a file.
# Basic usagebc <<< "10 + 5"# Output: 15
# With variablesnumber=42echo "sqrt($number)" | bc -l
# Using here-stringwc -w <<< "hello world test"# Output: 3IFS (Internal Field Separator)
Section titled “IFS (Internal Field Separator)”A variable that determines how Bash splits words. Default is space, tab, newline.
# Default (whitespace)text="one two three"for word in $text; do echo "$word"done
# Custom IFSIFS=',' read -ra fields <<< "a,b,c,d"echo "${fields[0]}" # a
# Parse CSVwhile IFS=',' read -r name email role; do echo "Name: $name, Email: $email"done < users.csv
# Real-world: Parse /etc/passwdwhile IFS=':' read -r user pass uid gid info home shell; do echo "User: $user (UID: $uid)"done < /etc/passwdIteration
Section titled “Iteration”The process of repeating a set of commands. Bash provides several loop constructs.
# For loop - iterate over listfor i in 1 2 3 4 5; do echo "Number: $i"done
# For loop - iterate over filesfor file in *.txt; do echo "Processing: $file"done
# For loop - C-stylefor ((i=0; i<10; i++)); do echo "Count: $i"done
# For loop - rangefor i in {1..5}; do echo "$i"done
# While loopcount=0while [[ $count -lt 5 ]]; do echo "Count: $count" ((count++))done
# Read file line by linewhile IFS= read -r line; do echo "Line: $line"done < file.txtJob Control
Section titled “Job Control”The ability to manage background and foreground processes.
# Start process in background./script.sh &
# List jobsjobs
# Bring to foregroundfg %1
# Send to backgroundbg %1
# Kill jobkill %1
# Multiple jobs./task1.sh &./task2.sh &wait # Wait for all background jobsKeyword
Section titled “Keyword”A reserved word that has special meaning to the shell (e.g., if, then, else, fi, for, while, do, done, case, esac, function, etc.).
# These are keywords:if then else elif fifor while until do donecase esac infunction selecttime coprocLocal Variable
Section titled “Local Variable”A variable limited to a specific scope (function). Without local, variables are global.
# Function with local variablegreeting="Hello"
say_hello() { local greeting="Hi" echo "$greeting"}
say_helloecho "$greeting" # Prints: Hello (global unchanged)Loop Control
Section titled “Loop Control”Commands that modify loop behavior: break, continue.
# Break - exit loop earlyfor i in {1..10}; do if [[ $i -eq 5 ]]; then break fi echo "$i"done
# Continue - skip iterationfor i in {1..5}; do if [[ $i -eq 3 ]]; then continue fi echo "$i"done
# Nested loops - break outerfor i in {1..3}; do for j in {1..3}; do if [[ $j -eq 2 ]]; then break 2 # Break outer loop fi donedoneMetacharacter
Section titled “Metacharacter”A character that has special meaning to the shell.
# Shell metacharacters| # Pipe& # Background; # Command separator( ) # Subshell/grouping{ } # Command grouping< > # Redirection$ # Variable prefix" ' # Quoting\ # Escape# # Comment? # Glob single char* # Glob any chars[ ] # Character class~ # TildeNameref
Section titled “Nameref”A variable that references another variable by name. Useful for dynamic variable access.
# Basic namerefvar1="value1"var2="value2"name="var1"
declare -n ref="$name"echo "$ref" # value1
# Change via namerefref="newvalue"echo "$var1" # newvalue (original changed!)
# Function with nameref (for output variables)get_config() { local -n config="$1" config[host]="prod.example.com"}
declare -A settingsget_config settingsecho "${settings[host]}"Operator
Section titled “Operator”A symbol that performs an operation. Bash has several types.
# Arithmetic operators+ - * / % ** # Add, subtract, multiply, divide, modulo, power+= -= *= /= %= # Assignment operators
# Comparison operators (numeric)-eq -ne -lt -le -gt -ge
# Comparison operators (string)= == != < > -z -n
# File test operators-e -f -d -L -r -w -x -s
# Logical operators! # Not&& # And|| # Or
# Redirection operators> >> < << <<< 2> 2>> &>Parameter
Section titled “Parameter”A variable that holds a value. Can be positional, special, or user-defined.
# Positional parameters$0 # Script name$1 # First argument${10} # Tenth+ argument$# # Number of arguments$@ # All arguments (each as separate)$* # All arguments (as single string)
# Special parameters$$ # Current process ID$! # Last background PID$? # Exit status$- # Current option flags
# Variable parametersname="John" # Simple assignmentreadonly CONST="X" # Read-onlydeclare -i num=5 # Integerdeclare -a arr=() # Arraydeclare -A dict=() # Associative array (bash 4+)
# Parameter expansion${var:-default} # Default if unset${var:=default} # Assign default if unset${var:?message} # Error if unset${var:+alternate} # Alternate if set${#var} # Length of var${var:offset} # Substring from offset${var:offset:len} # Substring length${var#pattern} # Remove shortest prefix${var##pattern} # Remove longest prefix${var%pattern} # Remove shortest suffix${var%%pattern} # Remove longest suffix${var/pattern/string} # Replace first${var//pattern/string} # Replace all${var^^} # Uppercase all${var,,} # Lowercase allPattern Matching
Section titled “Pattern Matching”Using wildcards and regex to match strings.
# Glob patternsfile*.txt # file.txt, file1.txt, myfile.txt?.log # a.log, x.log (single char)[abc].txt # a.txt, b.txt, c.txt[!0-9]* # Not starting with digit
# Extended globs (shopt -s extglob)!(*.log) # Not .log files*.?(txt|md) # Optional match
# Regex (inside [[ ]])[[ "$var" =~ ^regex$ ]]
# Examplesip="192.168.1.1"[[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]
# Capture groupsdate="2024-01-15"[[ "$date" =~ ([0-9]{4})-([0-9]{2})-([0-9]{2}) ]]echo "${BASH_REMATCH[1]}" # 2024Pipeline
Section titled “Pipeline”A sequence of commands where output of one becomes input of next.
# Basic pipelinecat log.txt | grep ERROR | wc -l
# Complex pipelinefind /var/log -name "*.log" -mtime -7 | \ xargs grep -l ERROR | \ head -10
# Process substitution as pipeline alternativediff <(ls dir1) <(ls dir2)
# Pipeline with pipefailset -o pipefailPositional Parameters
Section titled “Positional Parameters”Arguments passed to a script or function.
# Accessing positional parametersecho "Script: $0"echo "Arg 1: $1"echo "Total args: $#"echo "All args: $@"
# Shift argumentsshift # $2 becomes $1
# With arraysargs=("$@")echo "${args[0]}"
# Parsing options with getoptswhile getopts "hvs:" opt; do case $opt in h) help; exit 0 ;; v) verbose=true ;; s) setting="$OPTARG" ;; esacdoneshift $((OPTIND -1))Process Substitution
Section titled “Process Substitution”A way to provide a command’s output as a file.
# Compare outputsdiff <(ls dir1) <(ls dir2)
# While with command outputwhile read -r line; do process "$line"done < <(find . -name "*.txt")
# Multiple inputscat <(echo "a") <(echo "b")
# Real-world: Compare server configsdiff <(ssh server1 "cat /etc/nginx/nginx.conf") \ <(ssh server2 "cat /etc/nginx/nginx.conf")Quote Removal
Section titled “Quote Removal”The final step of shell expansion where quotes are removed from the expanded text.
# After expansion, quotes are removedecho "Hello $name" # Double quotes removed, variables expanded
# Single quotes - literalecho 'Hello $name' # Output: Hello $name (no expansion)
# Escape - literal characterecho "Value: \$var" # Output: Value: $varQuoting
Section titled “Quoting”Using quotes to control word splitting and expansion.
# Double quotes - allow expansionecho "Hello $name"echo "Current dir: $(pwd)"
# Single quotes - literalecho 'Hello $name' # No expansion
# Differencevar="world"echo "Hello $var" # Hello worldecho 'Hello $var' # Hello $var
# With spacesfilename="my document.txt"cat "$filename" # WorksRedirection
Section titled “Redirection”Changing the default input/output of a command.
# Output redirectioncommand > file # overwritecommand >> file # append
# Input redirectioncommand < file
# Error redirectioncommand 2> errors.txt
# Both stdout and stderrcommand > all.txt 2>&1command &> all.txt
# Redirect to /dev/nullcommand 2> /dev/nullcommand > /dev/null 2>&1
# File descriptor manipulationexec 3> file.txtecho "text" >&3exec 3>&-Return Statement
Section titled “Return Statement”Used to exit a function with a specified exit status.
# Return exit statusfunction myfunc { return 0 # Success}
function myfunc { return 1 # Failure}
# Using return valuemyfuncif [[ $? -eq 0 ]]; then echo "Success"fi
# Cannot return arbitrary values (use echo)get_date() { date +%Y-%m-%d}result=$(get_date)Shebang
Section titled “Shebang”The first line of a script specifying the interpreter.
#!/bin/bash # Bash (absolute path)#!/usr/bin/env bash # Bash (from PATH - recommended)#!/bin/sh # POSIX shell
# With options#!/bin/bash -e # Exit on error#!/usr/bin/env bash -euo pipefail # Strict modeA command-line interpreter that executes commands (bash, sh, zsh, fish, etc.).
# Check current shellecho "$SHELL"ps -p $$ -o comm=
# Available shellscat /etc/shells
# Bash versionbash --versionecho "$BASH_VERSION"Signal
Section titled “Signal”A software interrupt sent to a process. Used for inter-process communication.
# Common signals# 1 SIGHUP - Hangup# 2 SIGINT - Interrupt (Ctrl+C)# 9 SIGKILL - Force kill (cannot be caught)# 15 SIGTERM - Termination (graceful)
# Send signalkill -TERM $PIDkill -15 $PIDkill -KILL $PID
# Send to process by namepkill -TERM nginx
# Handle signals with trapcleanup() { echo "Cleaning up..." rm -f /tmp/tempfile exit 0}trap cleanup SIGTERM SIGINT EXITSource
Section titled “Source”Execute commands from a file in the current shell.
# Load functionssource functions.sh
# Load configurationsource .env
# Equivalent to .. config.shStrict Mode
Section titled “Strict Mode”A set of options that make scripts safer.
# Recommended strict modeset -euo pipefail# -e: Exit on error# -u: Exit on undefined variable# -o pipefail: Pipeline fails if any command fails
# For scripts#!/usr/bin/env bashset -euo pipefailSubshell
Section titled “Subshell”A child shell process created when using parentheses or command substitution.
# Subshell with parentheses( cd /tmp pwd # /tmp, but original dir unchanged)pwd # Original directory
# Command substitution (also subshell)result=$(cd /tmp && pwd)Test Command
Section titled “Test Command”Evaluate conditional expressions. Can use [ ] (POSIX) or [[ ]] (bash).
# Using testtest -f file.txt && echo "Exists"
# Using [ ][ -f file.txt ] && echo "Exists"
# Using [[ ]] (bash, more powerful)[[ -f file.txt ]] && echo "Exists"
# Combiningif [ -f "$file" ] && [ -s "$file" ]; then echo "File exists and is not empty"fiExecute commands when signals are received or certain conditions occur.
# Cleanup on exitcleanup() { rm -f /tmp/temp echo "Cleaned up"}trap cleanup EXIT
# Handle signalstrap 'echo "Interrupted"; exit 1' INT TERM
# Debug each commandtrap 'echo "Executing: $BASH_COMMAND"' DEBUG
# Error handlingerr() { echo "Error on line $LINENO" >&2}trap err ERRUlimit
Section titled “Ulimit”Control resource limits for processes.
# View limitsulimit -a
# Common limitsulimit -n # Open filesulimit -u # Max processes
# Set limitsulimit -n 4096Remove a variable or function.
# Remove variablevar="hello"unset varecho "$var"
# Remove functionfunction myfunc() { echo "test"; }unset -f myfunc
# Remove array elementarr=(one two three)unset arr[1]
# Check if variable is setif [[ -v var ]]; then echo "var is set"fiVariable
Section titled “Variable”A named value that can be changed. In bash, all variables are strings.
# Assignmentname="John"age=30
# Access with $echo "$name is $age years old"
# Read-onlyreadonly CONSTANT="value"
# Integer (arithmetic)declare -i num=5num="hello" # Results in 0
# Arraydeclare -a arr=(1 2 3)
# Associative arraydeclare -A dict
# Export to environmentexport VAR="value"Wildcard
Section titled “Wildcard”A character used in pattern matching. See Globbing.
# Common wildcards* # Any characters? # Single character[abc] # Character class[!abc] # NegatedBuild and execute command lines from standard input.
# Basic usageecho "file1 file2 file3" | xargs rm
# With findfind . -name "*.log" -mtime +7 | xargs rm
# Custom placeholderfind . -name "*.txt" | xargs -I {} mv {} {}.bak
# Parallel executionls *.jpg | xargs -P 4 -I {} convert {} -resize 50% {}.small.jpgZero-Exit Status
Section titled “Zero-Exit Status”Exit code 0 indicates success.
# Check zero-exitif command; then echo "Success"fi
# Force zero-exittrue# Returns 0Common Acronyms
Section titled “Common Acronyms”| Acronym | Full Form | Description |
|---|---|---|
| IFS | Internal Field Separator | Variable controlling word splitting |
| PID | Process ID | Unique process identifier |
| UID | User ID | User identifier |
| GID | Group ID | Group identifier |
| TTY | Teletype | Terminal device |
| EOF | End Of File | Marker for file end |
| STDIN | Standard Input | Default input (fd 0) |
| STDOUT | Standard Output | Default output (fd 1) |
| STDERR | Standard Error | Error output (fd 2) |
| CLI | Command Line Interface | Text-based interface |
| POSIX | Portable Operating System Interface | Standard compatibility |
| DevOps | Development Operations | Development + Operations |
| SRE | Site Reliability Engineering | Operations engineering |
| SysAdmin | System Administrator | System management role |
| SSH | Secure Shell | Encrypted remote access |
| cron | Chronological | Task scheduler |
| systemd | System Daemon | Service manager (Arch Linux) |
Arch Linux Specific Terms
Section titled “Arch Linux Specific Terms”| Term | Description |
|---|---|
pacman | Arch Linux package manager |
AUR | Arch User Repository - community packages |
yay | Yet Another Yogurt - AUR helper |
paru | AUR helper - faster than yay |
makepkg | Build packages from source |
systemd | Init system and service manager |
journalctl | Query systemd journal logs |
systemctl | Control systemd system and services |
hostnamectl | Control system hostname |
timedatectl | Control system time and date |
DevOps/SRE Specific Terms
Section titled “DevOps/SRE Specific Terms”| Term | Description | Example |
|---|---|---|
| CI/CD | Continuous Integration/Deployment | Jenkins, GitLab CI, GitHub Actions |
| IaC | Infrastructure as Code | Terraform, CloudFormation |
| Container | Lightweight virtualization | Docker, Podman |
| Orchestration | Container management | Kubernetes, Docker Swarm |
| Monitoring | System observation | Prometheus, Grafana |
| Logging | Event recording | ELK Stack, Lokiing |
| AlertagerDuty, OpsGenie | ||
| Backup | Data protection | rsync, Borg, Restic |
End of Vocabulary. For more details, see the main guide.