Cheatsheets

Bash

Bash

Bash is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell.

7 Categories 30 Sections 46 Examples
Scripting Shell Linux Unix Command Line Automation

Getting Started

Fundamental Bash concepts and syntax for beginners.

Simple Script

Illustrates a basic Bash script structure and execution.

Basic script with variable

A basic Bash script that declares a variable and prints a greeting.

Code
#!/bin/bash
VAR="world"
echo "Hello $VAR!"
Execution
Terminal window
bash ./script.sh
Output
Terminal window
Hello world!
  • The shebang (#!/bin/bash) specifies the Bash interpreter.
  • Variables are assigned without spaces around '='.

Script with error handling

Uses 'set -e' to exit on errors and a default variable value if no argument is provided.

Code
#!/bin/bash
set -e
VAR="${1:-world}"
echo "Hello $VAR!"
Execution
Terminal window
bash ./script.sh universe
Input
Terminal window
universe
Output
Terminal window
Hello universe!
  • The 'set -e' ensures the script stops on any error.
  • Use ${VAR:-default} for fallback values.

Script Arguments

How to handle command-line arguments in Bash scripts.

Accessing positional arguments

Demonstrates accessing script name ($0), positional arguments ($1, $2), and argument count ($#).

Code
#!/bin/bash
echo "Script: $0"
echo "First arg: $1"
echo "Second arg: $2"
echo "Total args: $#"
Execution
Terminal window
bash ./args.sh hello world
Input
Terminal window
hello world
Output
Terminal window
Script: ./args.sh
First arg: hello
Second arg: world
Total args: 2
  • Quote arguments with spaces to treat as single arguments.
  • Use ${N} for arguments beyond $9.

Iterating over arguments

Uses $@ to iterate over arguments, preserving spaces.

Code
#!/bin/bash
for arg in "$@"; do
echo "Argument: $arg"
done
Execution
Terminal window
bash ./loop_args.sh "first arg" second
Input
Terminal window
first arg second
Output
Terminal window
Argument: first arg
Argument: second
  • Use "$@" to handle arguments with spaces correctly.

Functions

Defining and using functions in Bash scripts.

Basic function definition

Defines a simple function to greet a user.

Code
#!/bin/bash
function greet() {
echo "Hello, $1!"
}
greet "world"
Execution
Terminal window
bash ./greet.sh
Output
Terminal window
Hello, world!
  • 'function' keyword is optional in Bash.

Function with local variables

Demonstrates using local variables within a function.

Code
#!/bin/bash
function add() {
local sum=$(( $1 + $2 ))
echo "Sum: $sum"
}
add 5 10
Execution
Terminal window
bash ./add.sh
Output
Terminal window
Sum: 15
  • 'local' restricts the variable scope to the function.

Function with return status

Checks if a number is even using return status.

Code
#!/bin/bash
function check_even() {
if (( $1 % 2 == 0 )); then
return 0
else
return 1
fi
}
check_even 4
if [ $? -eq 0 ]; then
echo "Even"
else
echo "Odd"
fi
Execution
Terminal window
bash ./check_even.sh
Output
Terminal window
Even
  • $? captures the exit status of the last command.

Comments

Adding comments in Bash scripts for clarity.

Single-line comment

Demonstrates a single-line comment in Bash.

Code
Terminal window
# This is a single-line comment
  • Use '#' for single-line comments.

Multi-line comment

':' allows for multi-line comments.

Code
Terminal window
: 'This is a
multi-line comment
'
  • Use ': ' for multi-line comments.

Variables

Understanding and using variables in Bash scripts.

Declaring a variable

Declares a variable and prints its value.

Code
#!/bin/bash
VAR="Hello"
echo "$VAR"
Execution
Terminal window
bash ./var.sh
Output
Terminal window
Hello
  • Use double quotes to prevent word splitting.

Conditionals

Using if-else statements in Bash scripts.

Basic if statement

Checks if a string is empty or not using if-else statements.

Code
#!/bin/bash
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
fi
  • Use [[ ]] for conditional expressions.
  • Use -z to check if a string is empty.

Shell Execution

Executing shell commands from within a Bash script.

Executing a command

Executes the 'ls -l' command to list files in long format.

Code
#!/bin/bash
ls -l
Execution
Terminal window
bash ./exec.sh
Output
Terminal window
total 0
-rw-r--r-- 1 user group 0 Mar 15 12:00 file.txt
  • Use backticks or $() for command substitution.

Loops

Iterating over data and controlling loop flow in Bash.

For Loops

Iterating over lists, ranges, and using C-style for loops.

Basic for loop over files

Iterates over all files matching the glob pattern /etc/rc.* and prints each one.

Code
#!/bin/bash
for i in /etc/rc.*; do
echo "$i"
done
Execution
Terminal window
bash ./for_files.sh
Output
Terminal window
/etc/rc.common
/etc/rc.local
  • Glob patterns are expanded by the shell before the loop runs.
  • Always quote variables inside loops to handle spaces in filenames.

C-like for loop

Uses C-style syntax with double parentheses for arithmetic-based loops.

Code
#!/bin/bash
for ((i = 0; i < 5; i++)); do
echo "Index: $i"
done
Execution
Terminal window
bash ./c_for.sh
Output
Terminal window
Index: 0
Index: 1
Index: 2
Index: 3
Index: 4
  • Double parentheses (( )) allow arithmetic expressions.
  • Variables inside (( )) do not need the $ prefix.

Range loop

Uses brace expansion to generate a sequence from 1 to 5.

Code
#!/bin/bash
for i in {1..5}; do
echo "Number: $i"
done
Execution
Terminal window
bash ./range.sh
Output
Terminal window
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
  • Brace expansion does not work with variables; use seq or C-style loops instead.

Range loop with step size

Generates a range from 5 to 50 with a step size of 5.

Code
#!/bin/bash
for i in {5..50..5}; do
echo "$i"
done
Execution
Terminal window
bash ./range_step.sh
Output
Terminal window
5
10
15
20
25
30
35
40
45
50
  • The syntax is {start..end..step}.
  • Step size requires Bash 4.0 or newer.

While Loops

Repeating commands while a condition is true.

Basic while loop

Loops while count is less than 5, incrementing each iteration.

Code
#!/bin/bash
count=0
while [[ $count -lt 5 ]]; do
echo "Count: $count"
((count++))
done
Execution
Terminal window
bash ./while.sh
Output
Terminal window
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
  • Use [[ ]] for conditional tests in while loops.
  • (( )) is used for arithmetic increment.

Reading lines from a file

Reads a file line by line using input redirection.

Code
#!/bin/bash
while read -r line; do
echo "Line: $line"
done < file.txt
Execution
Terminal window
bash ./read_lines.sh
Output
Terminal window
Line: first line
Line: second line
  • The -r flag prevents backslash interpretation.
  • Input redirection < feeds the file into the while loop.

Infinite loop

Runs indefinitely until interrupted with Ctrl+C.

Code
#!/bin/bash
while true; do
echo "Press Ctrl+C to stop"
sleep 1
done
Execution
Terminal window
bash ./infinite.sh
Output
Terminal window
Press Ctrl+C to stop
Press Ctrl+C to stop
  • Use 'break' inside the loop to exit based on a condition.
  • Always include a sleep or wait to prevent CPU overuse.

Loop Control

Controlling loop execution with break, continue, and select.

Using break and continue

Skips 5 with continue and exits the loop at 8 with break.

Code
#!/bin/bash
for i in {1..10}; do
if [[ $i -eq 5 ]]; then
continue
fi
if [[ $i -eq 8 ]]; then
break
fi
echo "Number: $i"
done
Execution
Terminal window
bash ./control.sh
Output
Terminal window
Number: 1
Number: 2
Number: 3
Number: 4
Number: 6
Number: 7
  • continue skips to the next iteration.
  • break exits the loop entirely.

Select menu

Presents a numbered menu and executes the corresponding action.

Code
#!/bin/bash
select option in "Start" "Stop" "Quit"; do
case $option in
"Start") echo "Starting..." ;;
"Stop") echo "Stopping..." ;;
"Quit") break ;;
*) echo "Invalid option" ;;
esac
done
Execution
Terminal window
bash ./select.sh
Input
Terminal window
1
Output
Terminal window
1) Start
2) Stop
3) Quit
#? Starting...
  • select automatically generates a numbered menu.
  • Use break to exit the select loop.

Arrays

Working with indexed arrays in Bash.

Defining Arrays

Creating and initializing indexed arrays in Bash.

Defining an array

Defines an indexed array with three elements and prints each one.

Code
#!/bin/bash
Fruits=('Apple' 'Banana' 'Orange')
echo "${Fruits[0]}"
echo "${Fruits[1]}"
echo "${Fruits[2]}"
Execution
Terminal window
bash ./array.sh
Output
Terminal window
Apple
Banana
Orange
  • Array indices start at 0 in Bash.
  • Elements are separated by spaces inside parentheses.

Index assignment

Assigns values to specific indices; indices do not need to be contiguous.

Code
#!/bin/bash
Fruits[0]="Apple"
Fruits[1]="Banana"
Fruits[5]="Orange"
echo "${Fruits[@]}"
Execution
Terminal window
bash ./index_assign.sh
Output
Terminal window
Apple Banana Orange
  • Bash arrays are sparse; you can skip indices.
  • Use ${array[@]} to print all elements.

Array Operations

Common operations on Bash indexed arrays.

Accessing array elements

Demonstrates accessing first, last, all elements, count, slice, and keys of an array.

Code
#!/bin/bash
Fruits=('Apple' 'Banana' 'Orange' 'Mango' 'Kiwi')
echo "First: ${Fruits[0]}"
echo "Last: ${Fruits[-1]}"
echo "All: ${Fruits[@]}"
echo "Count: ${#Fruits[@]}"
echo "Slice: ${Fruits[@]:1:3}"
echo "Keys: ${!Fruits[@]}"
Execution
Terminal window
bash ./array_ops.sh
Output
Terminal window
First: Apple
Last: Kiwi
All: Apple Banana Orange Mango Kiwi
Count: 5
Slice: Banana Orange Mango
Keys: 0 1 2 3 4
  • Negative indices like ${Fruits[-1]} require Bash 4.2+.
  • ${Fruits[@]:offset:length} extracts a slice of the array.
  • ${!Fruits[@]} returns all valid indices.

Push, remove, and concatenate

Shows how to append, remove by pattern, unset by index, and merge arrays.

Code
#!/bin/bash
Fruits=('Apple' 'Banana' 'Orange')
# Push
Fruits+=('Mango')
echo "After push: ${Fruits[@]}"
# Remove by regex
Fruits=("${Fruits[@]/Ban*/}")
echo "After remove: ${Fruits[@]}"
# Unset by index
unset 'Fruits[2]'
echo "After unset: ${Fruits[@]}"
# Concatenate
Veggies=('Carrot' 'Pea')
Combined=("${Fruits[@]}" "${Veggies[@]}")
echo "Combined: ${Combined[@]}"
Execution
Terminal window
bash ./array_modify.sh
Output
Terminal window
After push: Apple Banana Orange Mango
After remove: Apple Orange Mango
After unset: Apple Mango
Combined: Apple Mango Carrot Pea
  • The += operator appends elements to an existing array.
  • Pattern removal may leave empty elements in the array.
  • unset removes the element but does not reindex the array.

Array Iteration

Iterating over array elements in Bash.

Iterating over array elements

Loops over each element in the array using "${array[@]}".

Code
#!/bin/bash
Fruits=('Apple' 'Banana' 'Orange')
for fruit in "${Fruits[@]}"; do
echo "Fruit: $fruit"
done
Execution
Terminal window
bash ./iterate.sh
Output
Terminal window
Fruit: Apple
Fruit: Banana
Fruit: Orange
  • Always quote "${array[@]}" to handle elements with spaces.
  • Use "${!array[@]}" to iterate over indices instead.

Dictionaries

Working with associative arrays (key-value pairs) in Bash.

Associative Arrays

Declaring and using associative arrays in Bash 4+.

Declaring and using an associative array

Creates an associative array of animal sounds and demonstrates access patterns.

Code
#!/bin/bash
declare -A sounds
sounds[dog]="bark"
sounds[cat]="meow"
sounds[bird]="tweet"
echo "Dog: ${sounds[dog]}"
echo "All values: ${sounds[@]}"
echo "All keys: ${!sounds[@]}"
echo "Count: ${#sounds[@]}"
Execution
Terminal window
bash ./assoc.sh
Output
Terminal window
Dog: bark
All values: tweet bark meow
All keys: bird dog cat
Count: 3
  • declare -A is required for associative arrays.
  • The order of keys is not guaranteed.
  • Requires Bash 4.0 or newer.

Deleting a key

Removes a key from the associative array using unset.

Code
#!/bin/bash
declare -A sounds
sounds[dog]="bark"
sounds[cat]="meow"
unset 'sounds[dog]'
echo "Remaining keys: ${!sounds[@]}"
echo "Remaining values: ${sounds[@]}"
Execution
Terminal window
bash ./assoc_delete.sh
Output
Terminal window
Remaining keys: cat
Remaining values: meow
  • Quote the key in unset to prevent glob expansion.

Dictionary Iteration

Iterating over keys and values in associative arrays.

Iterating over values and keys

Iterates over all values with ${sounds[@]} and all keys with ${!sounds[@]}.

Code
#!/bin/bash
declare -A sounds
sounds[dog]="bark"
sounds[cat]="meow"
sounds[bird]="tweet"
echo "=== Values ==="
for val in "${sounds[@]}"; do
echo "$val"
done
echo "=== Keys ==="
for key in "${!sounds[@]}"; do
echo "$key: ${sounds[$key]}"
done
Execution
Terminal window
bash ./dict_iter.sh
Output
Terminal window
=== Values ===
tweet
bark
meow
=== Keys ===
bird: tweet
dog: bark
cat: meow
  • The iteration order is not guaranteed for associative arrays.
  • Use "${!array[@]}" to get keys and access values via ${array[$key]}.

Parameter Expansions

Bash string manipulation and parameter expansion techniques.

String Substitution

Replacing and removing substrings using parameter expansion.

Replacing and removing substrings

Demonstrates single and global replacement, and prefix and suffix removal with parameter expansion.

Code
#!/bin/bash
name="John Smith"
echo "${name/J/j}"
echo "${name//o/0}"
file="hello.tar.gz"
echo "${file%.*}"
echo "${file%%.*}"
echo "${file#*.}"
echo "${file##*.}"
Execution
Terminal window
bash ./substitution.sh
Output
Terminal window
john Smith
J0hn Smith
hello.tar
hello
tar.gz
gz
  • ${var/pattern/replacement} replaces the first match.
  • ${var//pattern/replacement} replaces all matches.
  • ${var%pattern} removes the shortest suffix match.
  • ${var%%pattern} removes the longest suffix match.
  • ${var#pattern} removes the shortest prefix match.
  • ${var##pattern} removes the longest prefix match.

String Slicing

Extracting substrings and getting string length.

Substrings and length

Extracts substrings by offset and length, and gets string length.

Code
#!/bin/bash
name="Hello World"
echo "${name:0:5}"
echo "${name:6}"
echo "${name:(-5)}"
echo "${#name}"
Execution
Terminal window
bash ./slice.sh
Output
Terminal window
Hello
World
World
11
  • ${name:offset:length} extracts a substring.
  • ${name:(-N)} extracts from the end (parentheses required).
  • ${#name} returns the string length.

Default Values

Setting default values for unset or empty variables.

Default value expansions

Shows the four default value operators: use default, assign default, use alternative, and error if unset.

Code
#!/bin/bash
unset foo
echo "${foo:-default_val}"
echo "foo is: '${foo}'"
echo "${foo:=assigned_val}"
echo "foo is: '${foo}'"
echo "${foo:+replacement}"
unset bar
echo "${bar:?'bar is required'}" 2>&1 || true
Execution
Terminal window
bash ./defaults.sh
Output
Terminal window
default_val
foo is: ''
assigned_val
foo is: 'assigned_val'
replacement
bash: bar: bar is required
  • ${foo:-val} uses val if foo is unset or empty, without assigning.
  • ${foo:=val} assigns val to foo if unset or empty.
  • ${foo:+val} uses val only if foo IS set and non-empty.
  • ${foo:?message} prints error and exits if foo is unset or empty.

Case Manipulation

Changing string case using parameter expansion.

Case conversion

Converts strings to lowercase, uppercase, and toggles the first character.

Code
#!/bin/bash
str="Hello World"
echo "${str,,}"
echo "${str^^}"
echo "${str,}"
echo "${str^}"
Execution
Terminal window
bash ./case_manip.sh
Output
Terminal window
hello world
HELLO WORLD
hello World
Hello World
  • ${str,,} converts the entire string to lowercase.
  • ${str^^} converts the entire string to uppercase.
  • ${str,} lowercases only the first character.
  • ${str^} uppercases only the first character.
  • Requires Bash 4.0 or newer.

I/O and Redirection

Input/output redirection, heredocs, and process substitution in Bash.

Redirection

Redirecting standard input, output, and error streams.

Output and error redirection

Demonstrates common redirection operators for stdout, stderr, and stdin.

Code
#!/bin/bash
# Redirect stdout to file
echo "hello" > output.txt
# Append stdout to file
echo "world" >> output.txt
# Redirect stderr to file
ls /nonexistent 2> error.log
# Redirect stderr to stdout
ls /nonexistent 2>&1
# Redirect both stdout and stderr to file
ls /nonexistent &> all.log
# Discard output
ls /nonexistent 2>/dev/null
# Read stdin from file
cat < output.txt
Execution
Terminal window
bash ./redirect.sh
Output
Terminal window
hello
world
  • > overwrites the file; >> appends to it.
  • 2> redirects stderr only.
  • 2>&1 sends stderr to the same destination as stdout.
  • &> redirects both stdout and stderr.
  • < reads stdin from a file.

Heredoc and Herestring

Using heredocs and herestrings for multi-line and inline input.

Heredoc

Passes multi-line text to cat using a heredoc delimiter.

Code
#!/bin/bash
cat <<END
Hello
World
END
Execution
Terminal window
bash ./heredoc.sh
Output
Terminal window
Hello
World
  • The delimiter (END) must appear alone on its own line.
  • Variables inside heredocs are expanded by default.
  • Use <<'END' (quoted) to prevent variable expansion.

Herestring

Feeds a string directly to a command using the <<< operator.

Code
#!/bin/bash
read -r first second <<< "Hello World"
echo "First: $first"
echo "Second: $second"
Execution
Terminal window
bash ./herestring.sh
Output
Terminal window
First: Hello
Second: World
  • Herestrings pass a single string as stdin.
  • Useful as an alternative to echo "string" | command.

Reading Input

Reading user input from the terminal.

Reading user input

Reads a full line and a single character from user input.

Code
#!/bin/bash
read -r -p "Enter your name: " name
echo "Hello, $name!"
read -r -n 1 -p "Continue? (y/n) " answer
echo ""
echo "You chose: $answer"
Execution
Terminal window
bash ./read_input.sh
Input
Terminal window
Alice
y
Output
Terminal window
Enter your name: Hello, Alice!
Continue? (y/n) You chose: y
  • -r prevents backslash interpretation.
  • -p sets a prompt string.
  • -n 1 reads only one character.

Process Substitution

Using process substitution to treat command output as files.

Comparing two command outputs

Uses process substitution to compare directory listings without temporary files.

Code
#!/bin/bash
diff <(ls /usr/bin) <(ls /usr/local/bin)
Execution
Terminal window
bash ./procsub.sh
Output
Terminal window
< file_only_in_bin
> file_only_in_local_bin
  • <(command) provides command output as a file descriptor.
  • >(command) sends input to a command as a file descriptor.
  • This avoids the need for temporary files.

Advanced Bash

Advanced Bash techniques for robust scripting.

Strict Mode

Using strict mode options for safer Bash scripts.

Enabling strict mode

Enables strict mode that exits on errors, unset variables, and pipe failures.

Code
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
echo "Running in strict mode"
echo "Unset var: $UNSET_VAR"
Execution
Terminal window
bash ./strict.sh
Output
Terminal window
Running in strict mode
bash: UNSET_VAR: unbound variable
  • -e exits on any command failure.
  • -u treats unset variables as errors.
  • -o pipefail returns the exit code of the first failing command in a pipe.
  • IFS=$'\n\t' prevents word splitting on spaces.

Trap and Error Handling

Using trap for error handling and cleanup.

Trap on error

Traps ERR signal and prints the line number where the error occurred.

Code
#!/bin/bash
trap 'echo "Error at line $LINENO"' ERR
echo "Before error"
false
echo "This will not run"
Execution
Terminal window
bash ./trap_err.sh
Output
Terminal window
Before error
Error at line 6
  • ERR trap fires whenever a command returns a non-zero exit status.
  • $LINENO contains the current line number.

Trap for cleanup on exit

Uses EXIT trap to ensure temporary files are cleaned up when the script exits.

Code
#!/bin/bash
tmpfile=$(mktemp)
cleanup() {
rm -f "$tmpfile"
echo "Cleaned up $tmpfile"
}
trap cleanup EXIT
echo "Working with $tmpfile"
echo "data" > "$tmpfile"
Execution
Terminal window
bash ./trap_exit.sh
Output
Terminal window
Working with /tmp/tmp.XXXXXXXXXX
Cleaned up /tmp/tmp.XXXXXXXXXX
  • EXIT trap runs when the script finishes, regardless of how it exits.
  • Use trap for cleanup of temporary files, lock files, etc.

Case / Switch

Pattern matching with case/esac statements.

Case statement with patterns

Matches user input against patterns and executes the corresponding block.

Code
#!/bin/bash
read -r -p "Enter a fruit: " fruit
case "$fruit" in
"apple")
echo "Apple is red"
;;
"banana"|"plantain")
echo "Banana is yellow"
;;
"orange")
echo "Orange is orange"
;;
*)
echo "Unknown fruit: $fruit"
;;
esac
Execution
Terminal window
bash ./case_switch.sh
Input
Terminal window
banana
Output
Terminal window
Enter a fruit: Banana is yellow
  • Use | to match multiple patterns in one branch.
  • *) acts as the default/fallback case.
  • Each branch ends with ;; to stop matching.

Printf Formatting

Formatted output with printf.

Printf examples

Demonstrates printf with string, integer, float, and padding format specifiers.

Code
#!/bin/bash
printf "Hello %s\n" "World"
printf "Number: %d\n" 42
printf "Float: %.2f\n" 3.14159
printf "Padded: %10s|\n" "right"
printf "Padded: %-10s|\n" "left"
printf '%s\n' "line1" "line2" "line3"
Execution
Terminal window
bash ./printf.sh
Output
Terminal window
Hello World
Number: 42
Float: 3.14
Padded: right|
Padded: left |
line1
line2
line3
  • %s for strings, %d for integers, %f for floats.
  • printf does not add a newline automatically; use \n.
  • printf reuses the format string for extra arguments.

Special Variables

Built-in special variables in Bash.

Common special variables

Displays the most commonly used Bash special variables.

Code
#!/bin/bash
echo "Exit status of last command: $?"
echo "PID of current script: $$"
echo "Script name: $0"
echo "Last argument of previous command: $_"
echo "Random number: $RANDOM"
echo "Current line number: $LINENO"
sleep 0.1 &
echo "PID of last background process: $!"
wait
true | false | true
echo "PIPESTATUS: ${PIPESTATUS[@]}"
Execution
Terminal window
bash ./special.sh
Output
Terminal window
Exit status of last command: 0
PID of current script: 12345
Script name: ./special.sh
Last argument of previous command: ./special.sh
Random number: 28317
Current line number: 7
PID of last background process: 12346
PIPESTATUS: 0 1 0
  • $? is the exit status of the last command (0 = success).
  • $$ is the PID of the current shell.
  • $! is the PID of the last background process.
  • ${PIPESTATUS[@]} gives exit codes of all commands in the last pipeline.
  • $RANDOM generates a random integer between 0 and 32767.

Brace Expansion

Generating arbitrary strings with brace expansion.

Brace expansion patterns

Shows comma-separated, range, stepped, and combined brace expansions.

Code
#!/bin/bash
echo {A,B}.js
echo {1..5}
echo {1..10..2}
echo {a..z..3}
echo pre{fix,lude,pare}
echo {1..3}{a..c}
Execution
Terminal window
bash ./brace.sh
Output
Terminal window
A.js B.js
1 2 3 4 5
1 3 5 7 9
a d g j m p s v y
prefix prelude prepare
1a 1b 1c 2a 2b 2c 3a 3b 3c
  • {A,B} expands to each comma-separated item.
  • {1..5} generates a numeric sequence.
  • {1..10..2} generates a sequence with a step.
  • Brace expansion is performed before other expansions.

History Expansion

Reusing and modifying previous commands with history expansion.

History expansion operators

Demonstrates history expansion operators for recalling and modifying commands.

Code
Terminal window
# Re-run the last command
!!
# Last argument of the previous command
echo !$
# All arguments of the previous command
echo !*
# Run command number 42 from history
!42
# Replace text in the last command and re-run
!!:s/from/to/
  • !! repeats the entire last command.
  • !$ is the last argument of the previous command.
  • !* is all arguments of the previous command.
  • !n runs command number n from history.
  • !!:s/from/to/ substitutes text in the last command.
  • History expansion is mainly useful in interactive shells.