Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Bash

BashΒΆ


🧭 Navigation & File Management
CommandDescription
pwdPrint working directory
cd dirChange directory
cd ..Go up one level
cd ~Go to home directory
cd -Go to previous directory
lsList files
ls -laList all files with details
ls -lhHuman-readable file sizes
treeDirectory tree view
mkdir dirCreate directory
mkdir -p a/b/cCreate nested directories
rm fileDelete file
rm -rf dirDelete directory recursively
cp src dstCopy file
cp -r src dstCopy directory
mv src dstMove or rename
touch fileCreate empty file / update timestamp
ln -s target linkCreate symbolic link
πŸ“„ Viewing & Editing Files
CommandDescription
cat filePrint file contents
less filePage through file (q to quit)
head -n 20 fileFirst 20 lines
tail -n 20 fileLast 20 lines
tail -f fileFollow file (live updates)
wc -l fileCount lines
wc -w fileCount words
sort fileSort lines alphabetically
sort -n fileSort numerically
uniq fileRemove duplicate adjacent lines
sort file | uniq -cCount occurrences of each line
cut -d: -f1 fileCut field 1 using : delimiter
tr 'a-z' 'A-Z'Translate characters (lowercase to upper)
diff file1 file2Show differences between files
πŸ” Searching
CommandDescription
grep pattern fileSearch for pattern in file
grep -r pattern dirRecursive search in directory
grep -i pattern fileCase-insensitive search
grep -n pattern fileShow line numbers
grep -v pattern fileInvert match (exclude lines)
grep -l pattern dirList files with matches
grep -E 'a|b' fileExtended regex (OR)
find . -name "*.txt"Find files by name
find . -type f -mtime -7Files modified in last 7 days
find . -size +10MFiles larger than 10MB
locate filenameFast file search (uses index)
which cmdShow path of command
type cmdShow how a command is resolved
πŸ”€ Pipes, Redirection & I/O
SyntaxDescription
cmd1 | cmd2Pipe stdout of cmd1 to cmd2
cmd > fileRedirect stdout to file (overwrite)
cmd >> fileRedirect stdout to file (append)
cmd < fileRead stdin from file
cmd 2> fileRedirect stderr to file
cmd &> fileRedirect both stdout and stderr
cmd 2>&1Redirect stderr to stdout
cmd | tee fileWrite to file and also stdout
cmd1 && cmd2Run cmd2 only if cmd1 succeeds
cmd1 || cmd2Run cmd2 only if cmd1 fails
cmd1 ; cmd2Run cmd2 regardless of cmd1
$(cmd)Command substitution
`cmd`Command substitution (older syntax)
πŸ“¦ Variables & Strings

Variables

name="Alice"
echo $name
echo "${name}!"       # Use braces for clarity
readonly PI=3.14      # Constant
unset name            # Delete variable

Special variables

VariableDescription
$0Script name
$1 … $9Positional arguments
$@All arguments (array)
$#Number of arguments
$?Exit status of last command
$$PID of current shell
$!PID of last background process
$HOMEHome directory
$PATHExecutable search path
$PWDCurrent directory

String operations

str="Hello World"
echo ${#str}          # Length: 11
echo ${str:6}         # Substring: World
echo ${str:0:5}       # Substring: Hello
echo ${str/World/Bash}  # Replace: Hello Bash
echo ${str,,}         # Lowercase: hello world
echo ${str^^}         # Uppercase: HELLO WORLD
echo ${str% World}    # Strip suffix: Hello
echo ${str#Hello }    # Strip prefix: World
πŸ”’ Arithmetic
# Arithmetic expansion
echo $((3 + 4))
echo $((10 % 3))

# let
let x=5+3

# expr (older)
expr 5 + 3

# bc for floats
echo "scale=2; 10/3" | bc
OperatorDescription
+ - * /Basic arithmetic
%Modulo
**Exponentiation
++x / x++Pre/post increment
--x / x--Pre/post decrement
πŸ” Control Flow

if / elif / else

if [ "$x" -gt 10 ]; then
  echo "big"
elif [ "$x" -eq 10 ]; then
  echo "ten"
else
  echo "small"
fi

Test operators

OperatorDescription
-eq -ne -lt -le -gt -geNumeric comparison
= !=String equality
-z strString is empty
-n strString is non-empty
-f fileFile exists and is regular
-d fileDirectory exists
-e fileFile or directory exists
-r -w -xReadable / writable / executable

for loop

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

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

for ((i=0; i<5; i++)); do
  echo $i
done

while / until

while [ "$count" -lt 5 ]; do
  echo $count
  ((count++))
done

until [ "$count" -ge 5 ]; do
  ((count++))
done

case

case "$var" in
  start) echo "Starting" ;;
  stop)  echo "Stopping" ;;
  *)     echo "Unknown" ;;
esac
🧩 Functions
greet() {
  local name="$1"          # local variable
  echo "Hello, $name!"
  return 0                 # exit status
}

greet "Alice"
result=$(greet "Bob")      # capture output
FeatureSyntax
Define functionname() { ... }
Call functionname arg1 arg2
Local variablelocal var=value
Return statusreturn N (0=success)
Access args$1, $2, $@
πŸ“‹ Arrays
# Indexed array
arr=(one two three)
echo ${arr[0]}          # one
echo ${arr[@]}          # all elements
echo ${#arr[@]}         # length: 3
arr+=(four)             # append
unset arr[1]            # remove element

# Associative array (Bash 4+)
declare -A map
map[key]="value"
echo ${map[key]}
echo ${!map[@]}         # all keys
echo ${map[@]}          # all values
πŸ“œ Script Basics

Template

#!/usr/bin/env bash
set -euo pipefail       # strict mode
IFS=$'\n\t'

main() {
  echo "Args: $@"
}

main "$@"

set options

OptionDescription
set -eExit on error
set -uError on undefined variable
set -o pipefailCatch errors in pipes
set -xPrint each command (debug)
set +xDisable debug

Input

read -p "Enter name: " name
read -s -p "Password: " pass   # silent input
read -t 10 input                # timeout

Exit codes

exit 0    # success
exit 1    # general error
exit 2    # misuse of command
echo $?   # check last exit code
βš™οΈ Process Management
CommandDescription
ps auxList all running processes
top / htopInteractive process viewer
kill PIDSend SIGTERM to process
kill -9 PIDForce kill (SIGKILL)
pkill nameKill by process name
jobsList background jobs
bg %NResume job N in background
fg %NBring job N to foreground
cmd &Run command in background
nohup cmd &Run immune to hangup
waitWait for all background jobs
sleep NPause for N seconds
time cmdMeasure execution time
🌐 Environment & Shell Config
export VAR=value         # export to child processes
printenv                 # print all env variables
env VAR=x cmd            # run cmd with modified env
source ~/.bashrc         # reload config
. script.sh              # source script (same shell)

# PATH management
export PATH="$HOME/.local/bin:$PATH"

# Aliases
alias ll='ls -la'
alias gs='git status'
unalias ll

.bashrc essentials

# Prompt
export PS1="\u@\h:\w\$ "

# History
export HISTSIZE=10000
export HISTFILESIZE=20000
export HISTCONTROL=ignoredups:erasedups
shopt -s histappend

# Auto-complete
bind 'set show-all-if-ambiguous on'
πŸ’‘ Tips & Tricks
  • Brace expansion: mkdir -p project/{src,tests,docs} creates all three dirs

  • Glob patterns: * any chars, ? one char, [abc] character class, ** recursive (with shopt -s globstar)

  • History shortcuts: !! last command, !$ last argument, Ctrl+r reverse search

  • Here-doc: cat << EOF ... EOF for multiline strings

  • Here-string: cmd <<< "string" feed string as stdin

  • Parameter defaults: ${var:-default} use default if unset, ${var:=default} assign default if unset

  • String length check: [[ -z "$var" ]] empty, [[ -n "$var" ]] non-empty

  • Null device: cmd > /dev/null 2>&1 suppress all output

  • xargs: find . -name "*.log" | xargs rm pass results as arguments

  • Script directory: DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"