---
title: "Bash"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/bash
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# 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 Categories30 Sections46 ExamplesPublished: 01 Jan 2023

ScriptingShellLinuxUnixCommand LineAutomation

[Markdown for AI(opens in a new tab)](/bash/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Linux & System Administration](/series/linux--system-administration)2/12

[PreviousAWK](/cheatsheets/awk)[NextChmod](/cheatsheets/chmod)

All posts in this series (12)

Cheatsheets12

1.  [AWK](/cheatsheets/awk)
2.  [BashYou are here](/cheatsheets/bash)
3.  [Chmod](/cheatsheets/chmod)
4.  [Cron](/cheatsheets/cron)
5.  [Curl](/cheatsheets/curl)
6.  [Find](/cheatsheets/find)
7.  [Grep](/cheatsheets/grep)
8.  [Netcat](/cheatsheets/nc)
9.  [Netstat](/cheatsheets/netstat)
10.  [Sed](/cheatsheets/sed)
11.  [SSH](/cheatsheets/ssh)
12.  [Linux Networking](/cheatsheets/linux-networking)

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.

The sections below cover Bash commands, syntax, and examples.

[Getting Started](#category-getting-started)

-   [Simple Script](#section-simple-script)
-   [Script Arguments](#section-script-arguments)
-   [Functions](#section-functions)
-   [Comments](#section-comments)
-   [Variables](#section-variables)
-   [Conditionals](#section-conditionals)
-   [Shell Execution](#section-shell-execution)

[Loops](#category-loops)

-   [For Loops](#section-for-loops)
-   [While Loops](#section-while-loops)
-   [Loop Control](#section-loop-control)

[Arrays](#category-arrays)

-   [Defining Arrays](#section-defining-arrays)
-   [Array Operations](#section-array-operations)
-   [Array Iteration](#section-array-iteration)

[Dictionaries](#category-dictionaries)

-   [Associative Arrays](#section-associative-arrays)
-   [Dictionary Iteration](#section-dictionary-iteration)

[Parameter Expansions](#category-parameter-expansions)

-   [String Substitution](#section-string-substitution)
-   [String Slicing](#section-string-slicing)
-   [Default Values](#section-default-values)
-   [Case Manipulation](#section-case-manipulation)

[I/O and Redirection](#category-io-and-redirection)

-   [Redirection](#section-redirection)
-   [Heredoc and Herestring](#section-heredoc-herestring)
-   [Reading Input](#section-reading-input)
-   [Process Substitution](#section-process-substitution)

[Advanced Bash](#category-advanced-bash)

-   [Strict Mode](#section-strict-mode)
-   [Trap and Error Handling](#section-trap-errors)
-   [Case / Switch](#section-case-switch)
-   [Printf Formatting](#section-printf-formatting)
-   [Special Variables](#section-special-variables)
-   [Brace Expansion](#section-brace-expansion)
-   [History Expansion](#section-history-expansion)

No commands found

Try adjusting your search term

## Getting Started

Fundamental Bash concepts and syntax for beginners.

### Simple Script

Illustrates a basic Bash script structure and execution.

#### Accessibility

Ensure output is clear and labeled for screen readers.

#### Best Practices

-   Always include a shebang line (#!/bin/bash).
-   Quote variables to prevent word splitting.
-   Use 'set -e' for basic error handling.

#### Common Errors

-   **Spaces around = in assignment:** Use VAR=value, not VAR = value.
-   **Missing execute permissions:** Run 'chmod +x script.sh' before execution.

#### Keywords

scriptbashshebangechovariableexecute

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html)

#### 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 -eVAR="${1:-world}"echo "Hello $VAR!"
```

Execution

Terminal window

```
bash ./script.sh universe
```

Input

Terminal window

```
universe
```

Output

Terminal window

```
Hello universe!
```

-   The 'set -e' makes the script stop on the first error.
-   Use ${VAR:-default} for fallback values.

### Script Arguments

How to handle command-line arguments in Bash scripts.

#### Accessibility

Label argument outputs clearly for screen reader compatibility.

#### Best Practices

-   Validate input arguments to prevent errors.
-   Use "$@" for iterating over arguments.
-   Provide default values with ${VAR:-default}.

#### Common Errors

-   **Unquoted $\* causing word splitting:** Use "$@" instead of $\* for argument iteration.

#### Advanced Notes

-   **Argument Processing:** Use 'shift' to process and remove arguments one by one.
-   **Validation:** Check if arguments are provided using \[ -z "$1" \].
-   **Default Values:** Use ${VAR:-default} for fallback values.

#### Keywords

argumentsparametersbashscript

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html)

#### Accessing positional arguments

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

Code

```
#!/bin/bashecho "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.shFirst arg: helloSecond arg: worldTotal 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/bashfor 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 argArgument: second
```

-   Use "$@" to handle arguments with spaces correctly.

### Functions

Defining and using functions in Bash scripts.

#### Accessibility

Ensure function outputs are clear and labeled for screen readers.

#### Best Practices

-   Use descriptive names for functions.
-   Document function purpose and parameters.

#### Common Errors

-   **'command not found' when calling a function:** 'source' the script or use './script.sh'.

#### Advanced Notes

-   **Function Parameters:** Use $1, $2, ... for positional parameters.
-   **Return Values:** Use 'return' for exit status, not for values.
-   **Local Variables:** Use 'local' to define variables within a function.

#### Keywords

functionsbashscript

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Functions.html)

#### 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 4if [ $? -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.

#### Accessibility

Ensure comments are clear and concise.

#### Best Practices

-   Use comments to explain complex logic.
-   Keep comments concise and relevant.

#### Common Errors

-   **Comment not recognized:** Start comments with '#'.
-   **Multi-line comment not working:** Use ': <<' for multi-line comments.

#### Advanced Notes

-   **Commenting Style:** Use '#' for single-line comments and ': <<' for multi-line comments.
-   **Documentation:** Consider using 'docstring' style for function documentation.

#### Keywords

commentsbashscript

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Comments.html)

#### 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 amulti-line comment'
```

-   Use ': ' for multi-line comments.

### Variables

Understanding and using variables in Bash scripts.

#### Accessibility

Ensure variable outputs are clear and labeled for screen readers.

#### Best Practices

-   Use uppercase for variable names.
-   Quote variables to prevent word splitting.

#### Common Errors

-   **'command not found' when using a variable:** 'source' the script or use './script.sh'.

#### Advanced Notes

-   **Variable Scope:** $VAR is global, local VAR is local to the function.
-   **'declare' command:** 'declare -i' for integer variables.

#### Keywords

variablesbashscript

#### 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.

#### Accessibility

Ensure conditional outputs are clear and labeled for screen readers.

#### Best Practices

-   Use spaces around brackets in conditions.
-   Quote variables to prevent word splitting.

#### Common Errors

-   **Missing spaces around brackets:** Use \[ condition \] instead of \[condition\].
-   **'command not found' when using if statement:** 'source' the script or use './script.sh'.

#### Advanced Notes

-   **Nested if statements:** You can nest if statements for complex conditions.
-   **Using 'elif':** 'elif' allows for multiple conditions.
-   **Using 'case':** 'case' is an alternative to multiple if-else statements.

#### Keywords

conditionalsifelsebashscript

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html)

#### 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.

#### Accessibility

Ensure command outputs are clear and labeled for screen readers.

#### Best Practices

-   Use '$(command)' for command substitution.
-   Quote variables to prevent word splitting.

#### Common Errors

-   **'command not found' when executing a command:** 'source' the script or use './script.sh'.
-   **Command substitution not working:** Use '$(command)' instead of \`command\`.

#### Advanced Notes

-   **Command substitution:** Use $(command) instead of \`command\` for better readability.
-   **Pipelines:** Use '|' to pipe output from one command to another.
-   **Redirection:** Use '>' to redirect output to a file.

#### Keywords

executionshellbashscript

#### 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.

#### Accessibility

Ensure loop outputs are clearly labeled for screen readers.

#### Best Practices

-   Use double quotes around variables inside loops to handle spaces.
-   Prefer C-style loops for numeric iteration with variables.
-   Use seq as a fallback when brace expansion with variables is needed.

#### Common Errors

-   **Brace expansion not working with variables:** Use C-style for loop or seq: for i in $(seq 1 $n); do
-   **Missing 'do' or 'done' keywords:** Give every 'for' a matching 'do' and 'done'.

#### Keywords

forloopiteraterangebash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Looping-Constructs.html)

#### 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: 0Index: 1Index: 2Index: 3Index: 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: 1Number: 2Number: 3Number: 4Number: 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

```
5101520253035404550
```

-   The syntax is {start..end..step}.
-   Step size requires Bash 4.0 or newer.

### While Loops

Repeating commands while a condition is true.

#### Accessibility

Ensure loop outputs are clearly labeled for screen readers.

#### Best Practices

-   Always use 'read -r' to prevent backslash mangling.
-   Include a termination condition to avoid infinite loops.
-   Use 'sleep' in infinite loops to reduce CPU usage.

#### Common Errors

-   **Loop never terminates:** Change the loop condition inside the loop, or use 'break'.
-   **Variables modified inside loop not visible outside:** Avoid piping into while; use redirection instead.

#### Keywords

whileloopreadinfinitebash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Looping-Constructs.html)

#### Basic while loop

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

Code

```
#!/bin/bash
count=0while [[ $count -lt 5 ]]; do  echo "Count: $count"  ((count++))done
```

Execution

Terminal window

```
bash ./while.sh
```

Output

Terminal window

```
Count: 0Count: 1Count: 2Count: 3Count: 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 lineLine: 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 1done
```

Execution

Terminal window

```
bash ./infinite.sh
```

Output

Terminal window

```
Press Ctrl+C to stopPress 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.

#### Accessibility

Ensure control flow outputs are clear for screen readers.

#### Best Practices

-   Use break to exit loops cleanly.
-   Use continue to skip iterations rather than nested if blocks.
-   Combine select with case for interactive menus.

#### Common Errors

-   **break or continue used outside a loop:** Put break and continue inside a for, while, or until loop.
-   **Select menu does not exit:** Add a break statement inside the quit option.

#### Keywords

breakcontinueselectloopcontrolbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html)

#### 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: 1Number: 2Number: 3Number: 4Number: 6Number: 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" ;;  esacdone
```

Execution

Terminal window

```
bash ./select.sh
```

Input

Terminal window

```
1
```

Output

Terminal window

```
1) Start2) Stop3) 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.

#### Accessibility

Ensure array outputs are clearly labeled for screen readers.

#### Best Practices

-   Use parentheses syntax for initializing arrays with multiple elements.
-   Quote array expansions to preserve elements with spaces.
-   Use 'declare -a' for explicit array declaration.

#### Common Errors

-   **Spaces around = in array assignment:** Use Fruits=("Apple" "Banana"), not Fruits = ("Apple" "Banana").
-   **Forgetting quotes around elements with spaces:** Quote each element: Fruits=("Red Apple" "Yellow Banana").

#### Keywords

arraydefinedeclarebash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Arrays.html)

#### 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

```
AppleBananaOrange
```

-   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.

#### Accessibility

Ensure operation outputs are clearly labeled for screen readers.

#### Best Practices

-   Use += to append elements to arrays.
-   Use unset to remove specific elements by index.
-   Quote "${array\[@\]}" to preserve elements with spaces.

#### Common Errors

-   **Array not reindexed after unset:** Reassign the array: array=("${array\[@\]}") to reindex.
-   **Pattern removal leaving empty strings:** Filter empty elements after removal.

#### Keywords

arrayoperationspushremovelengthslicebash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Arrays.html)

#### 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: AppleLast: KiwiAll: Apple Banana Orange Mango KiwiCount: 5Slice: Banana Orange MangoKeys: 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')
# PushFruits+=('Mango')echo "After push: ${Fruits[@]}"
# Remove by regexFruits=("${Fruits[@]/Ban*/}")echo "After remove: ${Fruits[@]}"
# Unset by indexunset 'Fruits[2]'echo "After unset: ${Fruits[@]}"
# ConcatenateVeggies=('Carrot' 'Pea')Combined=("${Fruits[@]}" "${Veggies[@]}")echo "Combined: ${Combined[@]}"
```

Execution

Terminal window

```
bash ./array_modify.sh
```

Output

Terminal window

```
After push: Apple Banana Orange MangoAfter remove: Apple  Orange MangoAfter unset: Apple  MangoCombined: 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.

#### Accessibility

Ensure iteration outputs are clearly labeled for screen readers.

#### Best Practices

-   Always double-quote "${array\[@\]}" in for loops.
-   Use index-based iteration when you need the position.
-   Avoid unquoted ${array\[\*\]} as it joins on IFS.

#### Common Errors

-   **Elements with spaces split into separate items:** Use "${Fruits\[@\]}" instead of ${Fruits\[@\]}.

#### Keywords

arrayiterateloopforbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Arrays.html)

#### 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: AppleFruit: BananaFruit: 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+.

#### Accessibility

Ensure dictionary outputs are clearly labeled for screen readers.

#### Best Practices

-   Always use 'declare -A' before using an associative array.
-   Quote keys containing special characters.
-   Check if a key exists before accessing it.

#### Common Errors

-   **Associative array behaves like indexed array:** Declare it with declare -A; without that, Bash treats it as indexed.
-   **'declare: -A: invalid option':** Upgrade to Bash 4.0+ which supports associative arrays.

#### Keywords

associativearraydictionarydeclarebash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Arrays.html)

#### Declaring and using an associative array

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

Code

```
#!/bin/bash
declare -A soundssounds[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: barkAll values: tweet bark meowAll keys: bird dog catCount: 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 soundssounds[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: catRemaining values: meow
```

-   Quote the key in unset to prevent glob expansion.

### Dictionary Iteration

Iterating over keys and values in associative arrays.

#### Accessibility

Ensure iteration outputs are clearly labeled for screen readers.

#### Best Practices

-   Iterate over keys when you need both key and value.
-   Always quote array expansions in for loops.
-   Check array length before iterating.

#### Common Errors

-   **Iterating over values but needing keys:** Use "${!sounds\[@\]}" to iterate over keys.

#### Keywords

associativeiteratekeysvaluesbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Arrays.html)

#### Iterating over values and keys

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

Code

```
#!/bin/bash
declare -A soundssounds[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 ===tweetbarkmeow=== Keys ===bird: tweetdog: barkcat: 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.

#### Accessibility

Ensure substitution outputs are clearly labeled for screen readers.

#### Best Practices

-   Use %% and
-   Prefer parameter expansion over external tools like sed for simple replacements.
-   Use # for prefix removal and % for suffix removal.

#### Common Errors

-   **Confusing # and % directions:** Remember that # removes from the left (prefix) and % removes from the right (suffix).
-   **Pattern not matching as expected:** Use \* as a wildcard in patterns for flexible matching.

#### Keywords

substitutionreplaceprefixsuffixparameterexpansionbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html)

#### 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 SmithJ0hn Smithhello.tarhellotar.gzgz
```

-   ${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.

#### Accessibility

Ensure slicing outputs are clearly labeled for screen readers.

#### Best Practices

-   Use parentheses for negative offsets to avoid ambiguity with default values.
-   Use ${#var} instead of external commands for string length.
-   Combine slicing with conditionals for input validation.

#### Common Errors

-   **Negative offset without parentheses:** Use ${name:(-1)} not ${name:-1} which is default value syntax.

#### Keywords

substringslicelengthoffsetbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html)

#### 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

```
HelloWorldWorld11
```

-   ${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.

#### Accessibility

Ensure default value outputs are clearly labeled for screen readers.

#### Best Practices

-   Use ${foo:-val} for safe defaults without modifying the variable.
-   Use ${foo:=val} when you want to persist the default assignment.
-   Use ${foo:?msg} for required variables in scripts.

#### Common Errors

-   **Using := in a readonly or special variable context:** Use :- instead of := for variables you do not want to modify.
-   **Script exiting unexpectedly:** Check for :? expansions on unset variables; they cause immediate exit.

#### Keywords

defaultfallbackunsetparameterexpansionbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html)

#### Default value expansions

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

Code

```
#!/bin/bash
unset fooecho "${foo:-default_val}"echo "foo is: '${foo}'"
echo "${foo:=assigned_val}"echo "foo is: '${foo}'"
echo "${foo:+replacement}"
unset barecho "${bar:?'bar is required'}" 2>&1 || true
```

Execution

Terminal window

```
bash ./defaults.sh
```

Output

Terminal window

```
default_valfoo is: ''assigned_valfoo is: 'assigned_val'replacementbash: 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.

#### Accessibility

Ensure case manipulation outputs are clearly labeled for screen readers.

#### Best Practices

-   Use case manipulation instead of tr or awk for simple conversions.
-   Remember these operators require Bash 4.0+.
-   Combine with conditionals for case-insensitive comparisons.

#### Common Errors

-   **Syntax error with ,, or ^^ operators:** Run Bash 4.0 or newer; older versions do not support this.

#### Keywords

lowercaseuppercasecaseparameterexpansionbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html)

#### 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 worldHELLO WORLDhello WorldHello 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.

#### Accessibility

Ensure redirection examples are clearly explained for screen readers.

#### Best Practices

-   Use >> to append and avoid overwriting important files.
-   Redirect stderr to /dev/null to suppress error messages.
-   Use &> when you want to capture all output.

#### Common Errors

-   **File overwritten unexpectedly:** Use >> to append instead of > which overwrites.
-   **Error messages still showing on screen:** Redirect stderr with 2> or 2>/dev/null.

#### Keywords

redirectstdoutstderrstdinfilebash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Redirections.html)

#### Output and error redirection

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

Code

```
#!/bin/bash
# Redirect stdout to fileecho "hello" > output.txt
# Append stdout to fileecho "world" >> output.txt
# Redirect stderr to filels /nonexistent 2> error.log
# Redirect stderr to stdoutls /nonexistent 2>&1
# Redirect both stdout and stderr to filels /nonexistent &> all.log
# Discard outputls /nonexistent 2>/dev/null
# Read stdin from filecat < output.txt
```

Execution

Terminal window

```
bash ./redirect.sh
```

Output

Terminal window

```
helloworld
```

-   \> 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.

#### Accessibility

Ensure heredoc examples are clearly structured for screen readers.

#### Best Practices

-   Use quoted delimiters (<<'END') when you do not want variable expansion.
-   Use herestrings instead of echo piping for simple cases.
-   Indent heredoc content with <<- and tabs for readability.

#### Common Errors

-   **Heredoc delimiter not recognized:** Remove leading spaces from the closing delimiter, or use <<- with tabs.
-   **Variables expanding unexpectedly in heredoc:** Quote the delimiter: <<'END' to prevent expansion.

#### Keywords

heredocherestringmultilineinputbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Redirections.html)

#### Heredoc

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

Code

```
#!/bin/bash
cat <<ENDHelloWorldEND
```

Execution

Terminal window

```
bash ./heredoc.sh
```

Output

Terminal window

```
HelloWorld
```

-   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: HelloSecond: World
```

-   Herestrings pass a single string as stdin.
-   Useful as an alternative to echo "string" | command.

### Reading Input

Reading user input from the terminal.

#### Accessibility

Ensure prompts are clear and accessible for screen readers.

#### Best Practices

-   Always use -r flag with read to prevent backslash mangling.
-   Provide clear prompts with -p for user-friendly scripts.
-   Validate input after reading.

#### Common Errors

-   **Backslashes disappearing from input:** Use read -r to preserve backslashes.
-   **Input not captured correctly:** Put the variable name after the read flags.

#### Keywords

readinputpromptinteractivebash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html)

#### Reading user input

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

Code

```
#!/bin/bash
read -r -p "Enter your name: " nameecho "Hello, $name!"
read -r -n 1 -p "Continue? (y/n) " answerecho ""echo "You chose: $answer"
```

Execution

Terminal window

```
bash ./read_input.sh
```

Input

Terminal window

```
Alicey
```

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.

#### Accessibility

Ensure process substitution examples are clearly explained for screen readers.

#### Best Practices

-   Use process substitution to avoid temporary files.
-   Combine with diff, comm, or paste for comparing outputs.
-   Remember that process substitution creates a subshell.

#### Common Errors

-   **Syntax error near unexpected token <(:** Run the script with Bash, not sh; process substitution is a Bash feature.
-   **Process substitution not working in scripts:** Use #!/bin/bash, not #!/bin/sh in the shebang line.

#### Keywords

processsubstitutiondiffbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html)

#### 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 more reliable scripting.

### Strict Mode

Using strict mode options for safer Bash scripts.

#### Accessibility

Ensure strict mode explanations are clear for screen readers.

#### Best Practices

-   Add 'set -euo pipefail' at the top of every script.
-   Set IFS=$'\\n\\t' to avoid unexpected word splitting.
-   Use || true for commands that are allowed to fail.

#### Common Errors

-   **Script exits unexpectedly with set -e:** Use || true for commands that may fail intentionally.
-   **Unbound variable error:** Use ${VAR:-default} to provide defaults for optional variables.

#### Keywords

strictsetpipefailerrexitnounsetbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html)

#### Enabling strict mode

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

Code

```
#!/bin/bash
set -euo pipefailIFS=$'\n\t'
echo "Running in strict mode"echo "Unset var: $UNSET_VAR"
```

Execution

Terminal window

```
bash ./strict.sh
```

Output

Terminal window

```
Running in strict modebash: 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.

#### Accessibility

Ensure trap examples are clearly explained for screen readers.

#### Best Practices

-   Use trap EXIT for cleanup tasks.
-   Use trap ERR for error logging and debugging.
-   Define cleanup functions for complex teardown logic.

#### Common Errors

-   **Trap not firing as expected:** Check the signal name (ERR, EXIT, INT, TERM).
-   **Cleanup function not defined when trap fires:** Define the function before the trap statement.

#### Keywords

traperrorcleanupexitsignalbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html)

#### 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"falseecho "This will not run"
```

Execution

Terminal window

```
bash ./trap_err.sh
```

Output

Terminal window

```
Before errorError 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 an EXIT trap so temporary files are removed 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.XXXXXXXXXXCleaned 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.

#### Accessibility

Ensure case statement outputs are clear for screen readers.

#### Best Practices

-   Always include a \*) default case.
-   Quote the variable in the case statement.
-   Use | for multiple patterns in a single branch.

#### Common Errors

-   **Missing ;; at end of case branch:** Every case branch must end with ;; (or ;& for fall-through).
-   **Patterns not matching:** Use glob patterns (\* and ?) for flexible matching.

#### Keywords

caseesacswitchpatternmatchingbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html)

#### Case statement with patterns

Matches user input against patterns and executes the corresponding block.

Code

```
#!/bin/bash
read -r -p "Enter a fruit: " fruitcase "$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.

#### Accessibility

Ensure printf outputs are clearly labeled for screen readers.

#### Best Practices

-   Use printf instead of echo for portable and predictable output.
-   Always include \\n for newlines explicitly.
-   Use printf for formatted tables and aligned output.

#### Common Errors

-   **Missing newline in printf output:** Add \\n to the format string: printf "text\\n".
-   **Wrong format specifier causing errors:** Match specifiers to argument types: %s for strings, %d for numbers.

#### Keywords

printfformatoutputstringbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html)

#### Printf examples

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

Code

```
#!/bin/bash
printf "Hello %s\n" "World"printf "Number: %d\n" 42printf "Float: %.2f\n" 3.14159printf "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 WorldNumber: 42Float: 3.14Padded:      right|Padded: left      |line1line2line3
```

-   %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.

#### Accessibility

Ensure special variable outputs are clearly labeled for screen readers.

#### Best Practices

-   Check $? immediately after the command you want to inspect.
-   Use ${PIPESTATUS\[@\]} with set -o pipefail for pipeline error handling.
-   Use $$ for creating unique temporary filenames.

#### Common Errors

-   **$? gives unexpected value:** $? is overwritten by every command; capture it immediately.
-   **$RANDOM not truly random:** $RANDOM is pseudo-random; use /dev/urandom for cryptographic needs.

#### Keywords

specialvariablesexitstatuspidbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html)

#### 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 | trueecho "PIPESTATUS: ${PIPESTATUS[@]}"
```

Execution

Terminal window

```
bash ./special.sh
```

Output

Terminal window

```
Exit status of last command: 0PID of current script: 12345Script name: ./special.shLast argument of previous command: ./special.shRandom number: 28317Current line number: 7PID of last background process: 12346PIPESTATUS: 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.

#### Accessibility

Ensure brace expansion outputs are clearly labeled for screen readers.

#### Best Practices

-   Use brace expansion for creating multiple files or directories quickly.
-   Combine brace expansions for Cartesian product generation.
-   Remember that brace expansion happens before variable expansion.

#### Common Errors

-   **Brace expansion not working with variables:** Brace expansion happens before variable expansion; use eval or seq instead.
-   **Spaces inside braces causing issues:** Do not use spaces inside brace expressions.

#### Keywords

braceexpansionsequencegeneratebash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html)

#### Brace expansion patterns

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

Code

```
#!/bin/bash
echo {A,B}.jsecho {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.js1 2 3 4 51 3 5 7 9a d g j m p s v yprefix prelude prepare1a 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.

#### Accessibility

Ensure history expansion examples are clearly explained for screen readers.

#### Best Practices

-   Use !! with sudo to repeat the last command as root.
-   !$ is a quick way to reuse the last argument.
-   Avoid history expansion in scripts; it is disabled by default.

#### Common Errors

-   **History expansion not working in scripts:** History expansion is disabled in non-interactive shells by default.
-   **Unexpected expansion with exclamation marks:** Use single quotes to prevent history expansion in interactive shells.

#### Keywords

historyexpansionrecallpreviouscommandbash

[Learn more](https://www.gnu.org/software/bash/manual/html_node/History-Interaction.html)

#### 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 commandecho !$
# All arguments of the previous commandecho !*
# 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.

Was this useful?

## Tags

#Scripting#Shell#Linux#Unix#Command Line#Automation

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fbash "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Bash&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fbash "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fbash&title=Bash&summary=Bash%20is%20a%20Unix%20shell%20and%20command%20language%20written%20by%20Brian%20Fox%20for%20the%20GNU%20Project%20as%20a%20free%20software%20replacement%20for%20the%20Bourne%20shell.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Bash%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fbash "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fbash&text=Bash "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fbash&title=Bash "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fbash&t=Bash "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fbash&media=&description=Bash%20is%20a%20Unix%20shell%20and%20command%20language%20written%20by%20Brian%20Fox%20for%20the%20GNU%20Project%20as%20a%20free%20software%20replacement%20for%20the%20Bourne%20shell. "Share on Pinterest")[Email](<mailto:?subject=Bash&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fbash>)

## Comments

## You might also enjoy

More posts on similar topics

## [AWK](/cheatsheets/awk)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Text Processing
-   Linux
-   Command Line
-   Development Tools
-   Scripting

AWK complete reference guide Quick start Print entire file awk '{ print }' file.txt# Print specific column awk '{ print $1 }' file.txt# Print lines matching pattern awk '/patter

#AWK#Text Processing#Pattern Matching+3 tags

[read more](/cheatsheets/awk)

## [Cron](/cheatsheets/cron)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   System Administration
-   Linux
-   Scheduling
-   Automation
-   Tools

Quick reference Field layout Min Hour Day Month Weekday Command\* /path/to/command ┬ ┬ ┬ ┬ ┬ │ │ │ │ └───── Weekday (0=Sunday,

#Cron#Crontab#Scheduling+3 tags

[read more](/cheatsheets/cron)

## [Find](/cheatsheets/find)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   File Operations
-   Tools

Best practices for find command usageAlways quote patterns to prevent shell expansion of special characters Use -type f first in find expressions for optimal performance \*\*Prune hea

#Find#File Search#Discovery+3 tags

[read more](/cheatsheets/find)

## [Chmod](/cheatsheets/chmod)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   File Management
-   Tools

Complete chmod reference covering file permissions, recursive changes with -v and -c, reference mode, logical operators, batch operations, practical examples, and security best practices for Linux fil

#Chmod#Permissions#File Permissions+5 tags

[read more](/cheatsheets/chmod)

## [Curl](/cheatsheets/curl)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Web Development
-   APIs
-   HTTP
-   Command Line
-   Tools

Getting started with Curl cURL (client URL) is a command-line tool for transferring data using URLs. It speaks HTTP, HTTPS, FTP, SFTP, and many other protocols, which makes it the usual choice for

#Curl#HTTP#REST+3 tags

[read more](/cheatsheets/curl)

## [Grep](/cheatsheets/grep)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   Text Processing
-   Tools

Best practices for grep usageAlways quote patterns to prevent shell interpretation of special characters Use -E flag for complex patterns to avoid escaping issues with basic regex

#Grep#Search#Pattern Matching+3 tags

[read more](/cheatsheets/grep)

6 related posts
