Bash Cheatsheet

Basics

Use this Bash reference while you build software engineering projects, review code, or refresh the syntax you reach for most.

Bash Cheatsheet for Software Engineering Practice

Use this Bash reference when you need shell scripting for portfolio projects, deployment scripts, coding take-homes, or technical interview prep. The examples focus on practical command-line patterns you can explain in a software engineer resume or code review: running scripts safely, handling arguments, redirecting output, and debugging with trace modes.

Shebang and Script Invocation

#!/usr/bin/env bash        # preferred: uses PATH to find bash
#!/bin/bash                # absolute path (common but less portable)

bash script.sh             # run with bash explicitly
./script.sh                # run directly (must be +x)
chmod +x script.sh         # make executable
bash -x script.sh          # trace execution (debug mode)
bash -n script.sh          # syntax check only (no execution)
bash -e script.sh          # exit on first error
bash -u script.sh          # error on unset variables
bash -o pipefail script.sh # propagate pipe errors

Common Options (set)

set -e                     # exit immediately on error
set -u                     # treat unset variables as errors
set -x                     # print each command before executing
set -o pipefail            # pipe fails if any command fails
set -euo pipefail          # common "safe mode" combination

set +e                     # disable exit-on-error
set +x                     # disable trace

# In a script header:
set -euo pipefail

Special Parameters

ParameterMeaning
$0Name of the script
$1$9Positional arguments 1–9
${10}Positional argument 10+ (braces required)
$#Number of positional arguments
$@All positional arguments (each separately quoted)
$*All positional arguments (single word when quoted)
$?Exit status of last command
$$PID of current shell
$!PID of last background process
$-Current shell options
$_Last argument of previous command
echo "Script: $0, Args: $#"
echo "All args: $@"
echo "Last exit: $?"
echo "PID: $$"

Comments

# This is a single-line comment

: '
This is a
multi-line comment block
(uses the no-op colon command)
'

echo "code"  # inline comment

Special Characters and Quoting

'literal string'           # single quotes: no expansion at all
"double quoted $var"       # double quotes: expands variables and $()
$'escape sequences'        # ANSI-C quoting: \n \t \\ etc.
\\                         # escape next character
echo "Tab:\tNewline:\n"    # \t \n NOT interpreted inside ""
echo $'Tab:\tNewline:\n'   # \t \n ARE interpreted here
printf "A\tB\n"            # printf always interprets \n \t

Basic I/O Commands

echo "hello"               # print to stdout (adds newline)
echo -n "no newline"       # suppress trailing newline
echo -e "line1\nline2"     # interpret escape sequences
printf "%-10s %d\n" name 42  # formatted output (preferred over echo)
printf '%s\n' "$var"       # safely print variable

read var                   # read line from stdin into var
read -p "Enter: " var      # display prompt before reading
read -s var                # silent (no echo, for passwords)
read -t 5 var              # timeout after 5 seconds
read -a arr                # read words into array
read -r line               # raw: don't interpret backslashes
read -d $'\0' var          # read until NUL byte

exit 0                     # exit with success
exit 1                     # exit with failure
exit $?                    # exit with last command's status

Exit Status and Boolean Operators

true                       # always exits 0
false                      # always exits 1
echo $?                    # print last exit status (0 = success)

command && echo "ok"       # run echo only if command succeeds
command || echo "failed"   # run echo only if command fails
command && echo "ok" || echo "failed"   # if/else one-liner

! command                  # negate exit status

Command Separators and Grouping

cmd1; cmd2                 # run sequentially (ignore exit status)
cmd1 && cmd2               # run cmd2 only if cmd1 succeeds
cmd1 || cmd2               # run cmd2 only if cmd1 fails
cmd1 | cmd2                # pipe stdout of cmd1 to stdin of cmd2
cmd1 |& cmd2               # pipe both stdout and stderr (bash 4+)

(cd /tmp && ls)            # subshell: changes don't affect parent
{ cd /tmp; ls; }           # current shell: changes DO affect parent
                           # note: space after { and semicolon before }

Background Jobs and Process Control

cmd &                      # run in background
wait                       # wait for all background jobs
wait $!                    # wait for last background job
wait $pid                  # wait for specific PID
jobs                       # list background jobs
fg %1                      # bring job 1 to foreground
bg %1                      # send job 1 to background
kill %1                    # kill job 1
kill -9 $pid               # force kill by PID
disown %1                  # remove job from job table (won't get HUP)
nohup cmd &                # run immune to hangup signal

Builtins Overview

:                          # no-op, always returns 0
.  file                    # source (same as source)
source file                # execute file in current shell
alias ll='ls -la'          # create alias
unalias ll                 # remove alias
type cmd                   # show how cmd would be interpreted
which cmd                  # show path of cmd (external)
command -v cmd             # portable check if cmd exists
builtin cd                 # force use of builtin, not a function
help builtin               # show help for a builtin

History Expansion

!!                         # repeat last command
!n                         # repeat command number n
!string                    # repeat last command starting with string
!$                         # last argument of previous command
!^                         # first argument of previous command
^old^new                   # replace old with new in last command
history                    # show command history
history 20                 # show last 20 commands
history -c                 # clear history
Ctrl+R                     # reverse search history (interactive)

Keyboard Shortcuts (readline)

ShortcutAction
Ctrl+AMove to beginning of line
Ctrl+EMove to end of line
Ctrl+UDelete to beginning of line
Ctrl+KDelete to end of line
Ctrl+WDelete word before cursor
Alt+FMove forward one word
Alt+BMove backward one word
Ctrl+LClear screen
Ctrl+RReverse history search
Ctrl+CInterrupt current command
Ctrl+ZSuspend foreground process
Ctrl+DEOF / logout
TabAuto-complete