Skip to content

VOCABULARY

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.


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.

Terminal window
# Absolute path examples
/etc/nginx/nginx.conf
/usr/bin/bash
/var/log/syslog
/home/username/projects
# Using in scripts
CONFIG_FILE="/etc/myapp/config.conf"
if [[ -f "$CONFIG_FILE" ]]; then
source "$CONFIG_FILE"
fi
# Relative to script location
SCRIPT_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.

Terminal window
# Define alias
alias 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 ~/.bashrc
echo "alias ll='ls -la'" >> ~/.bashrc
# Reload bashrc
source ~/.bashrc
# List all aliases
alias
# Remove alias
unalias ll

Special characters that match positions in a string rather than characters. Essential for pattern matching in log analysis and validation.

Terminal window
# ^ - Start of string/line
echo "testing" | grep '^test' # Matches
echo "atesting" | grep '^test' # No match
# $ - End of string/line
echo "testing" | grep 'ing$' # Matches
echo "testingx" | grep 'ing$' # No match
# Word boundaries
echo "hello world" | grep '\bworld\b' # Matches whole word
# Real-world examples
# Validate IP address
ip="192.168.1.1"
if [[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Valid IP"
fi
# Validate email
email="user@example.com"
if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "Valid email"
fi

The process of evaluating arithmetic expressions using $(( )) syntax. Bash only supports integer arithmetic. Critical for numeric operations in scripts.

Terminal window
# Basic operations
result=$((5 + 3)) # result = 8
result=$((10 - 3)) # result = 7
result=$((4 * 5)) # result = 20
result=$((10 / 3)) # result = 3 (integer division)
result=$((10 % 3)) # result = 1 (modulo)
# Compound operations
result=$(( (5 + 3) * 2)) # result = 16
result=$(( 10 ** 2 )) # result = 100 (exponentiation, bash 4+)
# Variables
a=10
b=3
sum=$((a + b)) # 13
product=$((a * b)) # 30
quotient=$((a / b)) # 3
remainder=$((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 point
result=$(echo "scale=2; 10 / 3" | bc) # 3.33
result=$(echo "sqrt(2)" | bc -l) # 1.41

A variable that can hold multiple values. Bash supports indexed arrays (numeric keys) and associative arrays (string keys). Essential for handling lists in automation scripts.

Terminal window
# Create indexed array
fruits=(apple banana cherry orange)
# Access elements
echo "${fruits[0]}" # apple (first element)
echo "${fruits[-1]}" # orange (last element)
echo "${fruits[@]}" # all elements
echo "${#fruits[@]}" # array length (4)
# Slice array
echo "${fruits[@]:1:2}" # banana cherry (from index 1, length 2)
# Append elements
fruits+=(grape mango)
fruits=( "${fruits[@]}" "watermelon" )
# Modify element
fruits[0]="APPLE"
# Delete element
unset fruits[2] # Remove third element
# Array from command output
files=(*.log) # All .log files in current dir
lines=($(cat file.txt)) # Split by IFS
# Associative array (requires bash 4+)
declare -A user_info
user_info[name]="john"
user_info[role]="admin"
user_info[email]="john@example.com"
# Access
echo "${user_info[name]}" # john
echo "${!user_info[@]}" # name role email (keys)
echo "${user_info[@]}" # john admin john@example.com (values)
# Iterate
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
# Real-world: Server list
servers=(web-01 web-02 web-03 db-01 cache-01)
for server in "${servers[@]}"; do
echo "Checking $server..."
ssh "$server" "uptime"
done

A process that runs without controlling the terminal. Started with & operator. Essential for running multiple tasks in parallel in DevOps scripts.

Terminal window
# 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 process
wait $PID
echo "Task completed"
# Wait for multiple processes
./task1.sh &
PID1=$!
./task2.sh &
PID2=$!
wait $PID1 $PID2
echo "All tasks completed"
# Background with output redirection
./backup.sh > /var/log/backup.log 2>&1 &
# Check if process is running
if ps -p $PID > /dev/null 2>&1; then
echo "Process is running"
fi
# Kill background process
kill $PID
# List background jobs
jobs

Commands that are part of the shell itself. These execute faster than external commands as they don’t require spawning a new process.

CommandDescriptionDevOps Use Case
echoPrint to stdoutLogging, output
printfFormatted outputCSV generation, reports
readRead inputInteractive scripts
cdChange directoryAutomation scripts
pwdPrint working directoryPath verification
exportSet environmentCI/CD pipelines
sourceExecute fileLoading configs
aliasCommand shortcutCustom shortcuts
localDeclare local variableFunction scope
declareDeclare variable/arrayType definitions
typesetDeclare variableFunction scope (legacy)
readonlyMark as read-onlyConstants
shiftShift positional paramsArgument parsing
getoptsParse optionsCLI argument parsing
evalEvaluate string as commandDynamic commands
execReplace shell processScript execution
trapSignal handlerCleanup, signals
testConditional expressionConditionals
trueReturn successInfinite loops
falseReturn failureExit with error
setSet shell optionsDebugging, options
shoptShell optionsExtended features

A bash feature that generates strings from patterns. It occurs before any other expansion.

Terminal window
# Sequence generation
echo {1..5} # 1 2 3 4 5
echo {01..10} # 01 02 03 04 05 06 07 08 09 10
echo {a..f} # a b c d e f
echo {A..Z} # A B C D ... Z
# Letter sequences
echo {a,z,m} # a z m
# File combinations
touch file{1,2,3}.txt # file1.txt file2.txt file3.txt
mkdir -p project/{src,bin,tests,docs,config}
# Complex patterns
echo {log,error,access}.{txt,log}
# log.txt log.log error.txt error.log access.txt access.log
# Nested braces
echo {{A,B},{a,b}}
# A a B b
# Real-world examples
# Backup multiple files
cp file{,.backup}
# Create multiple directories
mkdir -p app/{config,controllers,models,views,public}
# Note: Brace expansion happens first - variables won't work inside
NAME="test"
echo {$NAME.txt} # Literal: {test.txt}

A multi-way branch construct similar to switch-case in other languages. Used for menu-driven scripts and option parsing.

Terminal window
# Basic syntax
case $variable in
pattern1)
command1
command2
;;
pattern2)
command3
;;
*)
default_command
;;
esac
# Real-world example: Service management
case $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 patterns
case $extension in
txt|log)
echo "Text file"
;;
jpg|png|gif)
echo "Image file"
;;
sh|bash)
echo "Shell script"
;;
*)
echo "Unknown type"
;;
esac

A set of characters enclosed in square brackets used in pattern matching.

Terminal window
# 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 filename
filename="report_2024.pdf"
if [[ "$filename" =~ ^[[:alnum:]_.-]+\.(pdf|docx?|xlsx?)$ ]]; then
echo "Valid filename"
fi

Replacing a command with its output. Critical for capturing command results in variables.

Terminal window
# 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 substitution
outer=$(echo $(inner_function))
outer=$(compute_value "$(get_config)")
# Preserve newlines
output=$(cat large_file.txt)
# Command substitution in variable assignment
BACKUP_DIR="/backup/$(date +%Y%m%d)"
IP_ADDRESS=$(curl -s ifconfig.me)
# Exit status with command substitution
output=$(command) || echo "Command failed"
# Better approach:
if output=$(command 2>&1); then
echo "Success: $output"
else
echo "Failed: $output"
fi

A shell command that groups multiple commands together.

Terminal window
# 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 commands
cmd1 | cmd2 | cmd3
# Arithmetic evaluation
((x = 5 + 3))
# Array evaluation
((arr=(1 2 3)))

An expression that evaluates to true or false, used in [[ ]] or [ ].

Terminal window
# 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 running
if systemctl is-active --quiet nginx; then
echo "Nginx is running"
fi

A subprocess running in parallel with the shell, with bidirectional communication. Advanced feature for interactive commands.

Terminal window
# Start bc as coprocess
coproc BC { bc -l; }
# Send input to coprocess
echo "sqrt(2)" >&${BC[1]}
# Read output from coprocess
read -r result <&${BC[0]}
echo "Result: $result"
# Using named coprocess
coproc BC { bc -l 2>&1; }
# Real-world: Database interaction
coproc 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 up
kill $DB_PID 2>/dev/null

Running Bash with debug options enabled. Essential for troubleshooting scripts.

Terminal window
# Trace execution (shows commands with expansion)
bash -x script.sh
# Verbose (shows input lines)
bash -v script.sh
# Check syntax without execution
bash -n script.sh
# Combine options
bash -xv script.sh
# Debug specific section
set -x # Enable tracing
commands_to_debug
set +x # Disable tracing
# ERR tracing (bash 4+)
set -e # Exit on error
set -o errtrace # ERR trap inherited
# DEBUG trap
trap 'echo "Executing: $BASH_COMMAND"' DEBUG
# EXIT trap (cleanup)
trap 'echo "Cleaning up..."; rm -f /tmp/temp' EXIT
# Use in script
#!/bin/bash
set -x # Start debugging
set -e # Exit on error
set -u # Exit on undefined variable
set -o pipefail # Pipeline fails if any command fails
# Production script template
#!/usr/bin/env bash
set -euo pipefail
trap 'err=$?; echo "Error at line $LINENO"; exit $err' ERR

A POSIX-compliant shell used as /bin/sh on many systems. Scripts using POSIX features are more portable.

Terminal window
# Check default shell
ls -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 compatibility
shellcheck -s sh script.sh

A variable that affects the behavior of processes and other programs. Critical in DevOps for configuration.

Terminal window
# Set environment variable
export 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
# Unset
unset APP_ENV
# View all
env
printenv
printenv HOME
# One-time export
APP_ENV=production ./script.sh
# In scripts
if [[ "$APP_ENV" == "production" ]]; then
echo "Running in production mode"
fi

A sequence of characters that represents a special character.

Terminal window
# Common escape sequences
\n # Newline
\t # Tab
\r # Carriage return
\\ # Backslash
\" # Double quote
\' # Single quote
\a # Alert (bell)
\b # Backspace
# Examples
echo -e "Line1\nLine2" # Two lines
echo -e "Col1\tCol2" # Tab-separated
# In printf
printf "Name:\t%s\nAge:\t%d\n" "John" 30

A numeric value returned by a command indicating success (0) or failure (non-zero). Foundation of error handling.

Terminal window
# Check exit status
ls /etc/passwd
echo $? # 0 (success)
ls /nonexistent
echo $? # 1 or 2 (failure)
# Using exit status in conditionals
if grep -q "pattern" file.txt; then
echo "Pattern found"
fi
# Capture exit status
grep "pattern" file.txt
status=$?
# 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 exit
exit 0 # Success
exit 1 # General error
exit 2 # Usage error

A unit of data separated by a delimiter (typically whitespace). Important for text processing.

Terminal window
# Default IFS splits on whitespace
line="one two three"
echo $line | awk '{print $1}' # one
echo $line | awk '{print $3}' # three
# Custom IFS
line="one,two,three"
IFS=',' read -ra fields <<< "$line"
echo "${fields[0]}" # one
# Using cut
echo "col1 col2 col3" | cut -d' ' -f1 # col1
# CSV processing
while IFS=',' read -r name email role; do
echo "User: $name, Email: $email"
done < users.csv

An integer that represents an open file for a process. Each process has file descriptors 0, 1, 2 by default.

DescriptorNameDescription
0stdinStandard input (keyboard)
1stdoutStandard output (terminal)
2stderrStandard error (terminal)
3-9customAvailable for custom use
Terminal window
# Redirect stdout to file
echo "hello" > output.txt
echo "world" >> output.txt
# Redirect stderr to file
grep "pattern" file 2> errors.txt
# Redirect both
command > output.txt 2>&1
command &> all.txt
# Redirect to /dev/null
command 2> /dev/null
command > /dev/null 2>&1
# Custom file descriptors
exec 3> file.txt
echo "Line 1" >&3
exec 3>&-
# Process substitution
diff <(ls dir1) <(ls dir2)

A reusable code block that performs a specific task. Essential for code organization.

Terminal window
# 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 compatible
backup_files() {
local source="$1"
local dest="$2"
echo "Backing up $source to $dest"
tar -czf "$dest" "$source"
return $?
}
# Call function
backup_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 5
echo "Square: $sq"

Pattern matching for filename expansion (wildcards). Performed after other expansions.

Terminal window
# Basic wildcards
* # Any characters (except /)
? # Single character
[abc] # Character class
[!abc] # Negated class
# Match all .txt files
ls *.txt
# Match files with single character
ls file?.log # file1.log, file2.log
# Match specific characters
ls file[123].log # file1.log, file2.log, file3.log
# Extended globbing (enable with shopt)
shopt -s extglob
ls !(*.log) # All files except .log
ls +(www|ftp)/*.log

An associative array implementation in Bash (called associative arrays). Requires bash 4+.

Terminal window
# Declare associative array
declare -A config
# Add key-value pairs
config[host]="localhost"
config[port]="8080"
config[database]="mydb"
# Access values
echo "${config[host]}" # localhost
# List all keys
echo "${!config[@]}" # host port database
# Iterate
for key in "${!config[@]}"; do
echo "$key = ${config[$key]}"
done
# Real-world: Server inventory
declare -A server_ips
server_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}"
}

A way to provide input to a command using inline text. Excellent for multi-line input.

Terminal window
# Basic here document
cat << EOF
This is line 1
This is line 2
Variable: $VAR
Subshell: $(date)
EOF
# Without variable expansion (quoted delimiter)
cat << 'EOF'
This is literal: $VAR
This won't expand either: $(date)
EOF
# Use in scripts: Generate config file
cat > /etc/myapp.conf <<-EOF
# My Application Configuration
host = ${DB_HOST:-localhost}
port = ${DB_PORT:-5432}
debug = false
EOF
# Use with commands
mysql -u root -p <<EOF
CREATE DATABASE IF NOT EXISTS myapp;
USE myapp;
SELECT * FROM users;
EOF

Input redirection using a string instead of a file.

Terminal window
# Basic usage
bc <<< "10 + 5"
# Output: 15
# With variables
number=42
echo "sqrt($number)" | bc -l
# Using here-string
wc -w <<< "hello world test"
# Output: 3

A variable that determines how Bash splits words. Default is space, tab, newline.

Terminal window
# Default (whitespace)
text="one two three"
for word in $text; do
echo "$word"
done
# Custom IFS
IFS=',' read -ra fields <<< "a,b,c,d"
echo "${fields[0]}" # a
# Parse CSV
while IFS=',' read -r name email role; do
echo "Name: $name, Email: $email"
done < users.csv
# Real-world: Parse /etc/passwd
while IFS=':' read -r user pass uid gid info home shell; do
echo "User: $user (UID: $uid)"
done < /etc/passwd

The process of repeating a set of commands. Bash provides several loop constructs.

Terminal window
# For loop - iterate over list
for i in 1 2 3 4 5; do
echo "Number: $i"
done
# For loop - iterate over files
for file in *.txt; do
echo "Processing: $file"
done
# For loop - C-style
for ((i=0; i<10; i++)); do
echo "Count: $i"
done
# For loop - range
for i in {1..5}; do
echo "$i"
done
# While loop
count=0
while [[ $count -lt 5 ]]; do
echo "Count: $count"
((count++))
done
# Read file line by line
while IFS= read -r line; do
echo "Line: $line"
done < file.txt

The ability to manage background and foreground processes.

Terminal window
# Start process in background
./script.sh &
# List jobs
jobs
# Bring to foreground
fg %1
# Send to background
bg %1
# Kill job
kill %1
# Multiple jobs
./task1.sh &
./task2.sh &
wait # Wait for all background jobs

A reserved word that has special meaning to the shell (e.g., if, then, else, fi, for, while, do, done, case, esac, function, etc.).

Terminal window
# These are keywords:
if then else elif fi
for while until do done
case esac in
function select
time coproc

A variable limited to a specific scope (function). Without local, variables are global.

Terminal window
# Function with local variable
greeting="Hello"
say_hello() {
local greeting="Hi"
echo "$greeting"
}
say_hello
echo "$greeting" # Prints: Hello (global unchanged)

Commands that modify loop behavior: break, continue.

Terminal window
# Break - exit loop early
for i in {1..10}; do
if [[ $i -eq 5 ]]; then
break
fi
echo "$i"
done
# Continue - skip iteration
for i in {1..5}; do
if [[ $i -eq 3 ]]; then
continue
fi
echo "$i"
done
# Nested loops - break outer
for i in {1..3}; do
for j in {1..3}; do
if [[ $j -eq 2 ]]; then
break 2 # Break outer loop
fi
done
done

A character that has special meaning to the shell.

Terminal window
# Shell metacharacters
| # Pipe
& # Background
; # Command separator
( ) # Subshell/grouping
{ } # Command grouping
< > # Redirection
$ # Variable prefix
" ' # Quoting
\ # Escape
# # Comment
? # Glob single char
* # Glob any chars
[ ] # Character class
~ # Tilde

A variable that references another variable by name. Useful for dynamic variable access.

Terminal window
# Basic nameref
var1="value1"
var2="value2"
name="var1"
declare -n ref="$name"
echo "$ref" # value1
# Change via nameref
ref="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 settings
get_config settings
echo "${settings[host]}"

A symbol that performs an operation. Bash has several types.

Terminal window
# 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>> &>

A variable that holds a value. Can be positional, special, or user-defined.

Terminal window
# 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 parameters
name="John" # Simple assignment
readonly CONST="X" # Read-only
declare -i num=5 # Integer
declare -a arr=() # Array
declare -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 all

Using wildcards and regex to match strings.

Terminal window
# Glob patterns
file*.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$ ]]
# Examples
ip="192.168.1.1"
[[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]
# Capture groups
date="2024-01-15"
[[ "$date" =~ ([0-9]{4})-([0-9]{2})-([0-9]{2}) ]]
echo "${BASH_REMATCH[1]}" # 2024

A sequence of commands where output of one becomes input of next.

Terminal window
# Basic pipeline
cat log.txt | grep ERROR | wc -l
# Complex pipeline
find /var/log -name "*.log" -mtime -7 | \
xargs grep -l ERROR | \
head -10
# Process substitution as pipeline alternative
diff <(ls dir1) <(ls dir2)
# Pipeline with pipefail
set -o pipefail

Arguments passed to a script or function.

Terminal window
# Accessing positional parameters
echo "Script: $0"
echo "Arg 1: $1"
echo "Total args: $#"
echo "All args: $@"
# Shift arguments
shift # $2 becomes $1
# With arrays
args=("$@")
echo "${args[0]}"
# Parsing options with getopts
while getopts "hvs:" opt; do
case $opt in
h) help; exit 0 ;;
v) verbose=true ;;
s) setting="$OPTARG" ;;
esac
done
shift $((OPTIND -1))

A way to provide a command’s output as a file.

Terminal window
# Compare outputs
diff <(ls dir1) <(ls dir2)
# While with command output
while read -r line; do
process "$line"
done < <(find . -name "*.txt")
# Multiple inputs
cat <(echo "a") <(echo "b")
# Real-world: Compare server configs
diff <(ssh server1 "cat /etc/nginx/nginx.conf") \
<(ssh server2 "cat /etc/nginx/nginx.conf")

The final step of shell expansion where quotes are removed from the expanded text.

Terminal window
# After expansion, quotes are removed
echo "Hello $name" # Double quotes removed, variables expanded
# Single quotes - literal
echo 'Hello $name' # Output: Hello $name (no expansion)
# Escape - literal character
echo "Value: \$var" # Output: Value: $var

Using quotes to control word splitting and expansion.

Terminal window
# Double quotes - allow expansion
echo "Hello $name"
echo "Current dir: $(pwd)"
# Single quotes - literal
echo 'Hello $name' # No expansion
# Difference
var="world"
echo "Hello $var" # Hello world
echo 'Hello $var' # Hello $var
# With spaces
filename="my document.txt"
cat "$filename" # Works

Changing the default input/output of a command.

Terminal window
# Output redirection
command > file # overwrite
command >> file # append
# Input redirection
command < file
# Error redirection
command 2> errors.txt
# Both stdout and stderr
command > all.txt 2>&1
command &> all.txt
# Redirect to /dev/null
command 2> /dev/null
command > /dev/null 2>&1
# File descriptor manipulation
exec 3> file.txt
echo "text" >&3
exec 3>&-

Used to exit a function with a specified exit status.

Terminal window
# Return exit status
function myfunc {
return 0 # Success
}
function myfunc {
return 1 # Failure
}
# Using return value
myfunc
if [[ $? -eq 0 ]]; then
echo "Success"
fi
# Cannot return arbitrary values (use echo)
get_date() {
date +%Y-%m-%d
}
result=$(get_date)

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 mode

A command-line interpreter that executes commands (bash, sh, zsh, fish, etc.).

Terminal window
# Check current shell
echo "$SHELL"
ps -p $$ -o comm=
# Available shells
cat /etc/shells
# Bash version
bash --version
echo "$BASH_VERSION"

A software interrupt sent to a process. Used for inter-process communication.

Terminal window
# Common signals
# 1 SIGHUP - Hangup
# 2 SIGINT - Interrupt (Ctrl+C)
# 9 SIGKILL - Force kill (cannot be caught)
# 15 SIGTERM - Termination (graceful)
# Send signal
kill -TERM $PID
kill -15 $PID
kill -KILL $PID
# Send to process by name
pkill -TERM nginx
# Handle signals with trap
cleanup() {
echo "Cleaning up..."
rm -f /tmp/tempfile
exit 0
}
trap cleanup SIGTERM SIGINT EXIT

Execute commands from a file in the current shell.

Terminal window
# Load functions
source functions.sh
# Load configuration
source .env
# Equivalent to .
. config.sh

A set of options that make scripts safer.

Terminal window
# Recommended strict mode
set -euo pipefail
# -e: Exit on error
# -u: Exit on undefined variable
# -o pipefail: Pipeline fails if any command fails
# For scripts
#!/usr/bin/env bash
set -euo pipefail

A child shell process created when using parentheses or command substitution.

Terminal window
# Subshell with parentheses
(
cd /tmp
pwd # /tmp, but original dir unchanged
)
pwd # Original directory
# Command substitution (also subshell)
result=$(cd /tmp && pwd)

Evaluate conditional expressions. Can use [ ] (POSIX) or [[ ]] (bash).

Terminal window
# Using test
test -f file.txt && echo "Exists"
# Using [ ]
[ -f file.txt ] && echo "Exists"
# Using [[ ]] (bash, more powerful)
[[ -f file.txt ]] && echo "Exists"
# Combining
if [ -f "$file" ] && [ -s "$file" ]; then
echo "File exists and is not empty"
fi

Execute commands when signals are received or certain conditions occur.

Terminal window
# Cleanup on exit
cleanup() {
rm -f /tmp/temp
echo "Cleaned up"
}
trap cleanup EXIT
# Handle signals
trap 'echo "Interrupted"; exit 1' INT TERM
# Debug each command
trap 'echo "Executing: $BASH_COMMAND"' DEBUG
# Error handling
err() {
echo "Error on line $LINENO" >&2
}
trap err ERR

Control resource limits for processes.

Terminal window
# View limits
ulimit -a
# Common limits
ulimit -n # Open files
ulimit -u # Max processes
# Set limits
ulimit -n 4096

Remove a variable or function.

Terminal window
# Remove variable
var="hello"
unset var
echo "$var"
# Remove function
function myfunc() { echo "test"; }
unset -f myfunc
# Remove array element
arr=(one two three)
unset arr[1]
# Check if variable is set
if [[ -v var ]]; then
echo "var is set"
fi

A named value that can be changed. In bash, all variables are strings.

Terminal window
# Assignment
name="John"
age=30
# Access with $
echo "$name is $age years old"
# Read-only
readonly CONSTANT="value"
# Integer (arithmetic)
declare -i num=5
num="hello" # Results in 0
# Array
declare -a arr=(1 2 3)
# Associative array
declare -A dict
# Export to environment
export VAR="value"

A character used in pattern matching. See Globbing.

Terminal window
# Common wildcards
* # Any characters
? # Single character
[abc] # Character class
[!abc] # Negated

Build and execute command lines from standard input.

Terminal window
# Basic usage
echo "file1 file2 file3" | xargs rm
# With find
find . -name "*.log" -mtime +7 | xargs rm
# Custom placeholder
find . -name "*.txt" | xargs -I {} mv {} {}.bak
# Parallel execution
ls *.jpg | xargs -P 4 -I {} convert {} -resize 50% {}.small.jpg

Exit code 0 indicates success.

Terminal window
# Check zero-exit
if command; then
echo "Success"
fi
# Force zero-exit
true
# Returns 0

AcronymFull FormDescription
IFSInternal Field SeparatorVariable controlling word splitting
PIDProcess IDUnique process identifier
UIDUser IDUser identifier
GIDGroup IDGroup identifier
TTYTeletypeTerminal device
EOFEnd Of FileMarker for file end
STDINStandard InputDefault input (fd 0)
STDOUTStandard OutputDefault output (fd 1)
STDERRStandard ErrorError output (fd 2)
CLICommand Line InterfaceText-based interface
POSIXPortable Operating System InterfaceStandard compatibility
DevOpsDevelopment OperationsDevelopment + Operations
SRESite Reliability EngineeringOperations engineering
SysAdminSystem AdministratorSystem management role
SSHSecure ShellEncrypted remote access
cronChronologicalTask scheduler
systemdSystem DaemonService manager (Arch Linux)

TermDescription
pacmanArch Linux package manager
AURArch User Repository - community packages
yayYet Another Yogurt - AUR helper
paruAUR helper - faster than yay
makepkgBuild packages from source
systemdInit system and service manager
journalctlQuery systemd journal logs
systemctlControl systemd system and services
hostnamectlControl system hostname
timedatectlControl system time and date

TermDescriptionExample
CI/CDContinuous Integration/DeploymentJenkins, GitLab CI, GitHub Actions
IaCInfrastructure as CodeTerraform, CloudFormation
ContainerLightweight virtualizationDocker, Podman
OrchestrationContainer managementKubernetes, Docker Swarm
MonitoringSystem observationPrometheus, Grafana
LoggingEvent recordingELK Stack, Lokiing
AlertagerDuty, OpsGenie
BackupData protectionrsync, Borg, Restic

End of Vocabulary. For more details, see the main guide.