liminfo

Bashref

Free reference guide: Bashref

File Ops

ls -la

List all files in detail

drwxr-xr-x 2 user group 4096 Jan 1 file.txt
find . -name "*.log" -mtime +7 -delete

Delete .log files older than 7 days

du -sh *

Show size of each directory

1.2G  node_modules
 48K  src
tar -czf archive.tar.gz dir/

Compress directory with gzip

rsync -avz src/ dest/

Sync only changed files

Text Processing

grep -rn 'pattern' .

Recursively search for pattern

./src/app.js:42: pattern found
sed -i 's/old/new/g' file

Replace all occurrences in file

awk '{print $1, $3}' file

Print columns 1 and 3

sort file | uniq -c | sort -rn

Sort by frequency

   42 error
   17 warning
    3 info
cut -d: -f1 /etc/passwd

Extract field by delimiter

Network

curl -s https://api.example.com | jq .

Call API and format JSON

ss -tlnp

Show listening ports

LISTEN 0 128 *:80 *:* users:(("nginx",pid=1234))
wget -q -O - https://example.com

Download URL to stdout

scp file user@host:/path/

Copy file to remote server

dig +short example.com

DNS lookup

93.184.216.34

System

ps aux | grep node

Find node processes

kill -9 $(lsof -t -i:3000)

Kill process on port 3000

top -bn1 | head -5

CPU/memory summary

df -h

Disk usage

/dev/sda1  50G  32G  16G  67% /
free -h

Memory usage

Mem:  15Gi  8.2Gi  4.1Gi

Git

git log --oneline -10

Last 10 commits summary

git diff --stat HEAD~1

Last commit change summary

git stash && git pull && git stash pop

Save changes, pull, restore

git log --author='name' --since='1 week ago'

Recent commits by author

git branch -d $(git branch --merged | grep -v main)

Delete merged branches

Permissions

chmod 755 script.sh

Make executable (rwxr-xr-x)

chown -R user:group dir/

Change ownership recursively

chmod +x *.sh

Add execute to all .sh files

umask 022

Set default file permissions

Scripting

#!/usr/bin/env bash set -euo pipefail

Robust script header

trap "rm -f /tmp/lock" EXIT

Cleanup on exit

readonly DIR="$(cd "$(dirname "$0")" && pwd)"

Absolute path of script directory

logger -t myscript "Started at $(date)"

Write to syslog

exec 2>/tmp/err.log

Redirect stderr to file

Debugging

bash -x script.sh

Run script with trace mode

+ echo Hello
Hello
set -x; some_command; set +x

Debug specific block only

strace -e trace=file cmd

Trace file system calls

time command

Measure command execution time

real 0m1.234s
user 0m0.012s

About Bashref

This Bash cheat sheet is a comprehensive, searchable quick reference for Linux shell scripting — covering the bash commands list developers, sysadmins, and DevOps engineers reach for every day. The Variables section covers all key bash scripting syntax: variable assignment (VAR=value, no spaces around =), reference with ${VAR}, default-value expansion (${VAR:-default} and ${VAR:=default}), string length (${#VAR}), readonly and export, positional parameters ($0–$9), argument count ($#), last exit code ($?), and current PID ($$). These are the building blocks of every shell script.

The Conditionals section is a complete bash if-else and test-operator reference: POSIX [ ] vs Bash [[ ]] extended tests, numeric comparison (-eq -ne -gt -lt -ge -le), string comparison (== != < >), file tests (-f -d -e -r -w -x), empty-string checks (-z -n), and the case/esac multi-branch construct. The Loops section covers bash for loop syntax (for-in, C-style), while, until, and break/continue. The Functions section covers definition syntax, return exit codes, and local variable scoping — plus practical one-liner examples for each construct.

Arrays and string manipulation round out the bash scripting reference. Indexed array declaration, element access (${arr[i]}), full expansion (${arr[@]}), length (${#arr[@]}), append (arr+=()), and associative arrays (declare -A) are all covered. The Strings section documents the full bash parameter expansion cheat sheet: prefix/suffix removal (# ## % %%), search-and-replace (/ //), substring (:offset:length), and case conversion (^^ ,,). The I/O section covers echo/printf, read, all redirection operators (> >> 2> &>), here-docs (<<), pipes, and command substitution ($()). Process control covers &, && ||, trap, wait, nohup, and set -euo pipefail. Each syntax entry includes a runnable code example you can copy and use immediately.

Key Features

  • Quick Cheatsheet: searchable bash commands list by category (files, text, network, system, git, permissions)
  • Syntax Reference: all bash scripting syntax with copy-ready examples — variables, if/else, loops, functions, arrays
  • Try It: side-by-side command + expected output examples to understand bash behavior at a glance
  • One-Liners: practical bash one-liner recipes for file operations, log analysis, CSV, parallel processing, and more
  • Variables: ${VAR:-default}, ${VAR:=default}, ${#VAR}, readonly, export, $0/$#/$?/$$
  • Conditionals: [ ] vs [[ ]], numeric/string/file test operators, -z/-n empty tests, case statement
  • String operations: # ## % %% prefix/suffix removal, / // substitution, :offset:length, ^^ ,, case conversion
  • Process control: & background, && || chaining, trap signal handler, wait, nohup, set -euo pipefail strict mode

Frequently Asked Questions

What is the difference between [ ] and [[ ]] in Bash?

[ ] is the POSIX test command (also known as test), available in all POSIX-compatible shells. [[ ]] is Bash's extended test construct, which adds pattern matching with ==, regex matching with =~, and logical operators && and || inside the brackets. With [ ], you must quote variables to prevent word splitting; with [[ ]], quoting is less critical. Prefer [[ ]] in Bash scripts for safer and more powerful conditionals.

What does set -euo pipefail do in a Bash script?

set -e causes the script to exit immediately when any command returns a non-zero exit code. set -u treats references to undefined variables as errors (instead of silently using empty string). set -o pipefail makes a pipeline fail if any command in the pipe fails (without it, only the last command's exit code matters). Combining these as set -euo pipefail at the top of your script is best practice for writing robust, production-quality shell scripts.

How does the ${VAR:-default} syntax work in Bash?

${VAR:-default} returns the value of VAR if it is set and non-empty, otherwise returns "default" without modifying VAR. ${VAR:=default} does the same but also assigns "default" to VAR if it was empty. ${VAR:+alt} returns "alt" if VAR is set and non-empty, otherwise returns empty. ${VAR:?error message} exits with an error message if VAR is unset or empty.

How do I use associative arrays (hash maps) in Bash?

Declare an associative array with declare -A mymap. Set values with mymap[key]="value". Access values with ${mymap[key]}. List all keys with ${!mymap[@]} and all values with ${mymap[@]}. Note that associative arrays require Bash 4.0 or later. On macOS, the default /bin/bash is version 3; install Bash 5 via Homebrew and use #!/usr/local/bin/bash or #!/opt/homebrew/bin/bash.

How do I remove file extensions or path prefixes from strings in Bash?

Bash parameter expansion handles this without external commands. ${f##*/} removes everything up to the last slash (gets filename from path). ${f%.*} removes the shortest suffix matching .* (removes last extension). ${f%%.*} removes the longest suffix matching .* (removes all extensions). ${f#*/} removes the shortest prefix matching */ (removes first path component). These are faster than using basename, dirname, or sed.

How does the trap command work in Bash?

trap allows you to register a command or function to run when your script receives a signal or exits. Common usage: trap "rm -f /tmp/lockfile" EXIT runs cleanup when the script exits for any reason. trap "echo Interrupted" INT catches Ctrl+C. trap "cleanup_func" TERM catches kill signals. trap "" SIGPIPE ignores broken pipe signals. Always use trap for cleanup of temporary files, lock files, or background processes in production scripts.

What is the difference between $@ and $* in Bash?

Both represent all positional parameters (script arguments). The critical difference is in quoting: "$@" expands to separate quoted strings — "$1" "$2" "$3" — preserving arguments with spaces. "$*" expands to a single string with all arguments joined by the first character of IFS (usually a space): "$1 $2 $3". Always use "$@" when passing arguments to other commands to correctly handle arguments that contain spaces.

How do I run commands in the background and wait for them in Bash?

Append & to run a command in the background: task1 & task2 &. Use wait to block until all background jobs complete: wait. Use wait $! to wait for the most recently launched background job. Capture PIDs for selective waiting: task1 & pid1=$!; task2 & pid2=$!; wait $pid1; wait $pid2. Use nohup command & to keep a job running after you log out (output goes to nohup.out by default).

What are the most useful bash one-liners for everyday Linux tasks?

Some of the most practical bash one-liners: (1) Find and delete files older than N days: find /path -mtime +7 -delete. (2) Count lines matching a pattern: grep -c "error" logfile. (3) Kill a process on a specific port: kill -9 $(lsof -t -i:3000). (4) Batch rename files: for f in *.JPG; do mv "$f" "${f%.JPG}.jpg"; done. (5) Sum a CSV column: awk -F, '{sum+=$2} END {print sum}' data.csv. (6) Monitor a file in real time: tail -f /var/log/syslog. (7) Compress a directory: tar -czf archive.tar.gz dir/. This bash cheat sheet includes all these patterns and more.