A quick reference for Bash โ the most common shell for Linux administration. Bookmark this page.
Navigation and Files
# Navigate
cd /path/to/dir
cd - # Previous directory
cd ~ # Home directory
pwd # Print working directory
# List files
ls -la # Long format, all files
ls -lh # Human-readable sizes
ls -lt # Sort by modification time
ls -lS # Sort by size
# File operations
cp source dest
cp -r dir/ dest/ # Copy directory recursively
mv old new # Move/rename
rm file # Delete file
rm -rf dir/ # Delete directory (careful!)
mkdir -p path/to/dir # Create nested directoriesText Processing
# Search
grep "pattern" file
grep -r "pattern" dir/ # Recursive search
grep -i "pattern" file # Case insensitive
grep -n "pattern" file # Show line numbers
grep -v "pattern" file # Invert match (exclude)
# Process text
cat file | head -20 # First 20 lines
cat file | tail -20 # Last 20 lines
tail -f /var/log/syslog # Follow log in real-time
wc -l file # Count lines
sort file | uniq -c | sort -rn # Count unique occurrences
# Find and replace
sed 's/old/new/g' file # Replace all occurrences
sed -i 's/old/new/g' file # In-place replace
awk '{print $1, $3}' file # Print columns 1 and 3
awk -F: '{print $1}' /etc/passwd # Use custom delimiterVariables and Control Flow
# Variables
NAME="world"
echo "Hello, $NAME"
echo "Path: ${HOME}/bin"
# Command substitution
DATE=$(date +%Y-%m-%d)
FILE_COUNT=$(ls | wc -l)
# Conditionals
if [ -f "/path/to/file" ]; then
echo "File exists"
elif [ -d "/path/to/dir" ]; then
echo "Directory exists"
else
echo "Not found"
fi
# Loops
for file in *.txt; do
echo "Processing $file"
done
for i in {1..10}; do
echo "Iteration $i"
done
while read -r line; do
echo "$line"
done < input.txtProcess Management
# View processes
ps aux # All processes
ps aux | grep nginx # Filter
top # Interactive process viewer
htop # Better interactive viewer
# Background jobs
command & # Run in background
jobs # List background jobs
fg %1 # Bring job 1 to foreground
bg %1 # Resume job 1 in background
nohup command & # Survive terminal close
# Kill processes
kill PID # Send SIGTERM
kill -9 PID # Force kill (SIGKILL)
pkill -f "process name" # Kill by name patternDisk and Network
# Disk
df -h # Disk space
du -sh dir/ # Directory size
du -sh * | sort -rh | head # Largest items in current dir
# Network
curl -s https://api.example.com | jq .
wget -q https://example.com/file.zip
ss -tlnp # Open listening ports
ip addr show # IP addresses
ping -c 4 example.com # Connectivity testPermissions
# Change permissions
chmod 755 script.sh # rwxr-xr-x
chmod +x script.sh # Add execute
chmod -R 644 dir/ # Recursive
# Change ownership
chown user:group file
chown -R user:group dir/Tips and Tricks
- Use
!!to repeat the last command:sudo !! - Use
ctrl+rfor reverse history search - Use
set -euo pipefailat the top of scripts for safety - Use
xargsto parallelize:find . -name "*.log" | xargs -P4 gzip - Use
trapfor cleanup:trap 'rm -f /tmp/lockfile' EXIT