Bash Quick Reference
Everything you need day‑to‑day – commands, scripting, and system administration.
Basic Commands
File Operations
ls– list directoryls -la– list with details and hiddencd– change directorypwd– print working directorymkdir dir– create directorytouch file– create empty file / update timestampcp src dest– copy file/directorymv src dest– move or renamerm file– remove filerm -rf dir– remove directory forcefullyln -s target link– symbolic link
File Viewing
cat file– display entire fileless file– view file interactivelyhead file– first 10 linestail file– last 10 linestail -f file– follow file (live)wc file– word/line/char countfind / -name "file"– search for filesgrep pattern file– search for patterndiff file1 file2– compare files
Permissions
chmod 755 file # rwxr-xr-x chmod +x script # make executable chown user:group file # change owner/group
Redirections
# Output redirection command > file # stdout to file (overwrite) command >> file # stdout to file (append) command 2> file # stderr to file command &> file # stdout + stderr to file # Input redirection command < file # read from file command << EOF # heredoc ... EOF # Pipes (stdout of one to stdin of another) command1 | command2 # Examples ls -la | grep ".txt" cat file | sort | uniq -c
Variables
# Define variable (no spaces around =) name="Alice" age=25 # Use variable echo $name echo "$name is $age years old" # Command substitution current_dir=$(pwd) files=$(ls) # Environment variables export PATH=$PATH:/custom/bin export EDITOR=vim # Read from user read -p "Enter your name: " username echo "Hello, $username" # Special variables # $0 – script name # $1..$9 – positional arguments # $# – number of arguments # $* – all arguments as a single string # $@ – all arguments as separate words # $? – exit status of last command # $$ – process ID of current script
Conditionals
if / elif / else
if [ condition ]; then # commands elif [ condition ]; then # commands else # commands fi
File Tests
# Common file tests [ -f "file" ] # file exists and is regular [ -d "dir" ] # directory exists [ -e "path" ] # path exists [ -r "file" ] # readable [ -w "file" ] # writable [ -x "file" ] # executable [ -s "file" ] # non‑empty # Example if [ -f "$1" ]; then echo "File exists" fi
String Tests
[ -z "$str" ] # string is empty [ -n "$str" ] # string is non‑empty [ "$a" = "$b" ] # strings equal [ "$a" != "$b" ] # strings not equal [[ "$a" > "$b" ]] # string comparison (lexicographic) # Example if [ -z "$name" ]; then echo "Name is empty" fi
Numeric Tests
[ "$a" -eq "$b" ] # equal [ "$a" -ne "$b" ] # not equal [ "$a" -lt "$b" ] # less than [ "$a" -le "$b" ] # less or equal [ "$a" -gt "$b" ] # greater than [ "$a" -ge "$b" ] # greater or equal # Example if [ "$age" -ge 18 ]; then echo "Adult" fi
Logical Operators
# AND [ condition1 ] && [ condition2 ] [ condition1 -a condition2 ] # (legacy) # OR [ condition1 ] || [ condition2 ] [ condition1 -o condition2 ] # (legacy) # NOT [ ! condition ] # Example if [ -f "$file" ] && [ -r "$file" ]; then cat "$file" fi
Case Statement
case "$var" in "start") echo "Starting..." ;; "stop") echo "Stopping..." ;; "restart") echo "Restarting..." ;; *) echo "Unknown command" ;; esac
Loops
for Loop
# Iterate over list for item in apple banana orange; do echo $item done # Iterate over range for i in {1..5}; do echo $i done # C‑style for for ((i=0; i<5; i++)); do echo $i done # Iterate over files for file in *.txt; do echo "Processing $file" done
while Loop
# Basic while i=1 while [ $i -le 5 ]; do echo $i ((i++)) done # Read lines from file while IFS= read -r line; do echo "$line" done < file.txt # Infinite loop while true; do echo "Running..." sleep 1 done
until Loop
# Runs until condition is true i=1 until [ $i -gt 5 ]; do echo $i ((i++)) done
Functions
# Define function function greet() { local name="$1" # local variable echo "Hello, $name!" return 0 } # Alternative syntax greet() { echo "Hello, $1!" } # Function with return value (exit status) is_even() { if [ $(("$1" % 2)) -eq 0 ]; then return 0 else return 1 fi } # Call function greet "Alice" if is_even 4; then echo "Even" fi # Function with output capture result=$(greet "Bob")
Arrays
# Define array fruits=(apple banana orange) fruits[3]=grape # Access elements echo ${fruits[0]} # apple echo ${fruits[@]} # all elements echo ${#fruits[@]} # length # Iterate over array for fruit in "${fruits[@]}"; do echo $fruit done # Slice array echo ${fruits[@]:1:2} # banana orange
String Manipulation
# Length str="Hello" echo ${#str} # 5 # Substring echo ${str:1:3} # ell # Replace first occurrence echo ${str/"l"/"x"} # Hexlo # Replace all occurrences echo ${str//"l"/"x"} # Hexxo # Remove prefix path="/home/user/file.txt" echo ${path#/home/} # user/file.txt echo ${path##*/} # file.txt (basename) # Remove suffix echo ${path%.txt} # /home/user/file echo ${path%/*} # /home/user (dirname) # Convert to uppercase/lowercase str="hello" echo ${str^^} # HELLO echo ${str,,} # hello
Script Header (Shebang)
#!/bin/bash # Script description set -e # exit on error set -u # exit on undefined variable set -x # debug mode (print commands) set -o pipefail # fail on pipe errors
Common Commands Reference
Process Management
ps aux– list processestop/htop– process monitorkill PID– send signalkill -9 PID– force killbg– background jobfg– foreground jobjobs– list background jobsnohup command &– run in background
System Info
uname -a– system infodf -h– disk usagedu -sh dir– directory sizefree -h– memory usagewhoami– current userwho– logged in usersdate– current date/timeuptime– system uptime
Text Processing Tools
grep
grep pattern file # search grep -i pattern file # case‑insensitive grep -v pattern file # invert match grep -r pattern dir/ # recursive grep -c pattern file # count matches grep -E "regex" file # extended regex
sed
sed 's/old/new/g' file # replace all sed -n '5p' file # print line 5 sed '/pattern/d' file # delete matching lines sed -i 's/old/new/g' file # in‑place edit
awk
awk '{print $1}' file # print first column awk '$2 > 10' file # filter by column awk -F ',' '{print $1}' file # custom delimiter awk 'BEGIN{FS=","} {print $2}' file
Best Practices
- Add shebang –
#!/bin/bashor#!/usr/bin/env bash. - Use
set -eto exit on error andset -ufor undefined variables. - Use
[[ ]]instead of[ ]for more features and safety. - Quote variables –
"$var"to prevent word splitting. - Use
localfor variables inside functions. - Use
$(command)instead of backticks for command substitution. - Use
printfinstead ofechofor formatting. - Use
read -rto prevent backslash interpretation. - Add usage messages –
echo "Usage: $0 arg1 arg2". - Use
trapfor cleanup on script exit. - Check exit status –
if ! command; then. - Use
shellcheckto validate your scripts.
📌 Quick Reference
Check Bash version:
Make script executable:
Run script:
Debug script:
Validate script:
bash --versionMake script executable:
chmod +x script.shRun script:
./script.sh or bash script.shDebug script:
bash -x script.shValidate script:
shellcheck script.sh