Bash Cheat Sheet

Comprehensive Bash commands, shell syntax, quoting, variables, redirection, pipelines, and day-to-day scripting patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Invocation and Help
Show Bash version
bash --version

# Print installed Bash version.

Start login shell
bash -l

# Start Bash as a login shell.

Start clean interactive shell
bash --noprofile --norc

# Start Bash without profile or rc files.

Run one command and exit
bash -lc 'echo "$SHELL" && pwd'

# Run a command string in a login shell.

Check script syntax
bash -n script.sh

# Parse a script without executing it.

Run with execution trace
bash -x script.sh

# Print commands as they execute.

## Shell Basics
Print previous exit status
echo $?

# Show exit status of previous command.

Run command sequence
mkdir -p tmp && cd tmp && pwd

# Run later commands only if earlier ones succeed.

Run fallback command
grep -q needle file.txt || echo 'not found'

# Run fallback command when previous command fails.

Group commands in current shell
{ echo start; date; echo end; }

# Run a grouped list in current shell.

Run commands in subshell
( cd /tmp && pwd )

# Run a grouped list in a subshell.

Pipeline commands
ps aux | grep nginx | grep -v grep

# Send output from one command to another.

Enable pipefail
set -o pipefail

# Make pipeline fail if any command fails.

## Redirection
Redirect stdout to file
echo 'hello' > out.txt

# Overwrite a file with command output.

Append stdout to file
echo 'hello' >> out.txt

# Append output to a file.

Redirect stderr to file
grep needle missing.txt 2> errors.log

# Write error output to a separate file.

Redirect stdout and stderr
command > all.log 2>&1

# Send both stdout and stderr to same file.

Discard command output
command > /dev/null 2>&1

# Silence both stdout and stderr.

Use a here document
cat <<'EOF'
line 1
$HOME is not expanded here
EOF

# Feed literal multiline input to a command.

Use a here string
grep -o '[0-9]\+' <<< 'order-123'

# Pass a short string to stdin.

Read file line by line
while IFS= read -r line; do echo "$line"; done < input.txt

# Read a file safely without trimming backslashes.