Bash

Essential Bash shell commands, scripting syntax, and shortcuts for efficient command-line usage.

cli
bashshelllinuxscriptingterminal

Variables

# Variable assignment (no spaces around =)
name="John"
age=25

# Using variables
echo $name
echo "Hello, ${name}!"

# Command substitution
current_date=$(date)
files=`ls -la`  # Older syntax

# Environment variables
export PATH="$PATH:/new/path"
export MY_VAR="value"

# Special variables
$0    # Script name
$1    # First argument
$#    # Number of arguments
$@    # All arguments as separate words
$*    # All arguments as single string
$$    # Current process ID
$?    # Exit status of last command

Conditionals

# If statement
if [ "$name" = "John" ]; then
  echo "Hello John"
elif [ "$name" = "Jane" ]; then
  echo "Hello Jane"
else
  echo "Hello stranger"
fi

# String comparisons
[ "$a" = "$b" ]   # Equal
[ "$a" != "$b" ]  # Not equal
[ -z "$a" ]       # Empty string
[ -n "$a" ]       # Non-empty string

# Numeric comparisons
[ "$a" -eq "$b" ]  # Equal
[ "$a" -ne "$b" ]  # Not equal
[ "$a" -lt "$b" ]  # Less than
[ "$a" -le "$b" ]  # Less than or equal
[ "$a" -gt "$b" ]  # Greater than
[ "$a" -ge "$b" ]  # Greater than or equal

# File tests
[ -e "$file" ]  # Exists
[ -f "$file" ]  # Is regular file
[ -d "$file" ]  # Is directory
[ -r "$file" ]  # Is readable
[ -w "$file" ]  # Is writable
[ -x "$file" ]  # Is executable
[ -s "$file" ]  # Size > 0

# Logical operators
[ "$a" ] && [ "$b" ]  # AND
[ "$a" ] || [ "$b" ]  # OR
! [ "$a" ]            # NOT

# Modern test syntax (Bash-specific)
[[ "$name" == "John" ]]
[[ "$name" =~ ^J.*n$ ]]  # Regex match

Loops

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

# For loop with range
for i in {1..10}; do
  echo $i
done

# For loop with step
for i in {0..20..2}; do
  echo $i  # 0, 2, 4, ...
done

# C-style for loop
for ((i=0; i<10; i++)); do
  echo $i
done

# Loop over files
for file in *.txt; do
  echo "$file"
done

# While loop
count=0
while [ $count -lt 5 ]; do
  echo $count
  ((count++))
done

# Until loop
count=0
until [ $count -ge 5 ]; do
  echo $count
  ((count++))
done

# Loop over lines in file
while IFS= read -r line; do
  echo "$line"
done < file.txt

Functions

# Function definition
greet() {
  echo "Hello, $1!"
}

# Alternative syntax
function greet {
  echo "Hello, $1!"
}

# Call function
greet "World"

# Return values
add() {
  local result=$(($1 + $2))
  echo $result
}
sum=$(add 5 3)

# Local variables
my_func() {
  local my_var="local"
  echo $my_var
}

Arrays

# Indexed arrays
fruits=("apple" "banana" "cherry")
fruits[3]="date"

# Access elements
echo ${fruits[0]}      # First element
echo ${fruits[@]}      # All elements
echo ${#fruits[@]}     # Array length
echo ${fruits[@]:1:2}  # Slice (start:length)

# Associative arrays (Bash 4+)
declare -A user
user[name]="John"
user[age]=25
echo ${user[name]}

# Iterate over array
for fruit in "${fruits[@]}"; do
  echo $fruit
done

# Iterate with index
for i in "${!fruits[@]}"; do
  echo "$i: ${fruits[$i]}"
done

String Manipulation

str="Hello World"

# Length
echo ${#str}  # 11

# Substring
echo ${str:0:5}   # Hello
echo ${str:6}     # World

# Replace
echo ${str/World/Bash}    # Replace first
echo ${str//l/L}          # Replace all

# Remove pattern
echo ${str#Hello }   # Remove prefix: "World"
echo ${str%World}    # Remove suffix: "Hello "
echo ${str##*/}      # Remove longest prefix
echo ${str%%/*}      # Remove longest suffix

# Case conversion (Bash 4+)
echo ${str^^}  # HELLO WORLD
echo ${str,,}  # hello world

# Default values
echo ${var:-default}   # Use default if unset
echo ${var:=default}   # Set default if unset
echo ${var:+alt}       # Use alt if set
echo ${var:?error}     # Error if unset

Input/Output

# Read user input
read -p "Enter name: " name
read -s -p "Password: " pass  # Silent input
read -t 5 -p "Quick! " ans    # Timeout

# Output
echo "Hello"
echo -e "Line1\nLine2"  # Enable escapes
printf "Name: %s, Age: %d\n" "$name" "$age"

# Redirection
command > file.txt     # Stdout to file (overwrite)
command >> file.txt    # Stdout to file (append)
command 2> error.txt   # Stderr to file
command &> all.txt     # Both to file
command < input.txt    # File to stdin
command 2>&1           # Stderr to stdout

# Pipes
ls -la | grep ".txt" | wc -l

# Here document
cat << EOF
Multiple
lines
of text
EOF

# Here string
grep "pattern" <<< "search this string"

Process Management

# Run in background
command &

# List jobs
jobs

# Foreground/Background
fg %1
bg %1

# Kill processes
kill PID
kill -9 PID     # Force kill
killall name    # Kill by name
pkill pattern   # Kill by pattern

# Process info
ps aux          # All processes
ps aux | grep name
pgrep pattern   # Find PID by pattern
top             # Interactive process viewer
htop            # Better process viewer

Useful Commands

# Find files
find /path -name "*.txt"
find /path -type f -mtime -7     # Modified in last 7 days
find /path -size +10M            # Larger than 10MB
find /path -exec command {} \;   # Execute on results

# Search in files
grep "pattern" file.txt
grep -r "pattern" /path          # Recursive
grep -i "pattern" file.txt       # Case insensitive
grep -n "pattern" file.txt       # Show line numbers
grep -v "pattern" file.txt       # Invert match

# Text processing
cat file.txt
head -n 10 file.txt
tail -n 10 file.txt
tail -f file.txt     # Follow file
sort file.txt
uniq file.txt
wc -l file.txt       # Count lines
cut -d',' -f1 file   # Cut columns
awk '{print $1}' file
sed 's/old/new/g' file

# File operations
cp source dest
mv source dest
rm file
rm -rf directory
mkdir -p path/to/dir
touch file.txt
chmod 755 file
chown user:group file

Scripting Best Practices

#!/bin/bash

# Exit on error
set -e

# Exit on undefined variable
set -u

# Exit on pipe failure
set -o pipefail

# Combined (recommended)
set -euo pipefail

# Debug mode
set -x  # Print commands as they execute

# Check if command exists
if command -v git &> /dev/null; then
  echo "git is installed"
fi

# Trap errors
trap 'echo "Error on line $LINENO"' ERR

# Cleanup on exit
cleanup() {
  rm -f "$temp_file"
}
trap cleanup EXIT

Keyboard Shortcuts

# Navigation
Ctrl + A    # Move to beginning of line
Ctrl + E    # Move to end of line
Ctrl + U    # Delete to beginning
Ctrl + K    # Delete to end
Ctrl + W    # Delete previous word
Alt + B     # Move back one word
Alt + F     # Move forward one word

# History
Ctrl + R    # Reverse search history
Ctrl + P    # Previous command
Ctrl + N    # Next command
!!          # Repeat last command
!$          # Last argument of previous command
!*          # All arguments of previous command
!n          # Execute command n from history

# Control
Ctrl + C    # Interrupt/Kill current command
Ctrl + Z    # Suspend current command
Ctrl + D    # Exit shell / EOF
Ctrl + L    # Clear screen