Pure Bash Bible

A collection of pure bash alternatives to external processes.

Dylan Araps

This book is for sale at http://leanpub.com/bash

This version was published on 2018-06-21

*   *   *   *   *

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do.

*   *   *   *   *

© 2018 Dylan Araps

Dedicated to Elise Anton.

FOREWORD

A collection of pure bash alternatives to external processes and programs. The bash scripting language is more powerful than people realise and most tasks can be accomplished without the need for or dependence on external programs.

Calling an external process in bash is expensive and excessive use will cause a noticeable slowdown. Scripts and programs written using built-in methods (where applicable) will be faster, require less dependencies and afford a better understanding of the language itself.

The content of this book provides a reference for solving problems encountered when writing programs and scripts in bash. Examples are in function format showcasing how to incorporate these solutions into code.

STRINGS

Trim leading and trailing white-space from string

This is an alternative to sed, awk, perl and other tools. The function below works by finding all leading and trailing white-space and removing it from the start and end of the string. The : built-in is used in place of a temporary variable.

Example Function:

1 trim_string() {
2     # Usage: trim_string "   example   string    "
3     : "${1#"${1%%[![:space:]]*}"}"
4     : "${_%"${_##*[![:space:]]}"}"
5     printf '%s\n' "$_"
6 }

Example Usage:

1 $ trim_string "    Hello,  World    "
2 Hello,  World
3
4 $ name="   John Black  "
5 $ trim_string "$name"
6 John Black

Trim all white-space from string and truncate spaces

This is an alternative to sed, awk, perl and other tools. The function below works by abusing word splitting to create a new string without leading/trailing white-space and with truncated spaces.

Example Function:

1 # shellcheck disable=SC2086,SC2048
2 trim_all() {
3     # Usage: trim_all "   example   string    "
4     set -f
5     set -- $*
6     printf '%s\n' "$*"
7     set +f
8 }

Example Usage:

1 $ trim_all "    Hello,    World    "
2 Hello, World
3
4 $ name="   John   Black  is     my    name.    "
5 $ trim_all "$name"
6 John Black is my name.

Use regex on a string

The result of bash’s regex matching can be used to replace sed for a large number of use-cases.

CAVEAT: This is one of the few platform dependant bash features. bash will use whatever regex engine is installed on the user’s system. Stick to POSIX regex features if aiming for compatibility.

CAVEAT: This example only prints the first matching group. When using multiple capture groups some modification is needed.

Example Function:

1 regex() {
2     # Usage: regex "string" "regex"
3     [[ $1 =~ $2 ]] && printf '%s\n' "${BASH_REMATCH[1]}"
4 }

Example Usage:

 1 $ # Trim leading white-space.
 2 $ regex '    hello' '^\s*(.*)'
 3 hello
 4
 5 $ # Validate a hex color.
 6 $ regex "#FFFFFF" '^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$'
 7 #FFFFFF
 8
 9 $ # Validate a hex color (invalid).
10 $ regex "red" '^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$'
11 # no output (invalid)

Example Usage in script:

 1 is_hex_color() {
 2     if [[ "$1" =~ ^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$ ]]; then
 3         printf '%s\n' "${BASH_REMATCH[1]}"
 4     else
 5         printf '%s\n' "error: $1 is an invalid color."
 6         return 1
 7     fi
 8 }
 9
10 read -r color
11 is_hex_color "$color" || color="#FFFFFF"
12
13 # Do stuff.

Split a string on a delimiter

This is an alternative to cut, awk and other tools.

Example Function:

1 split() {
2    # Usage: split "string" "delimiter"
3    IFS=$'\n' read -d "" -ra arr <<< "${1//$2/$'\n'}"
4    printf '%s\n' "${arr[@]}"
5 }

Example Usage:

 1 $ split "apples,oranges,pears,grapes" ","
 2 apples
 3 oranges
 4 pears
 5 grapes
 6
 7 $ split "1, 2, 3, 4, 5" ", "
 8 1
 9 2
10 3
11 4
12 5
13
14 # Multi char delimiters work too!
15 $ split "hello---world---my---name---is---john" "---"
16 hello
17 world
18 my
19 name
20 is
21 john

Change a string to lowercase

CAVEAT: Requires bash 4+

Example Function:

1 lower() {
2     # Usage: lower "string"
3     printf '%s\n' "${1,,}"
4 }

Example Usage:

1 $ lower "HELLO"
2 hello
3
4 $ lower "HeLlO"
5 hello
6
7 $ lower "hello"
8 hello

Change a string to uppercase

CAVEAT: Requires bash 4+

Example Function:

1 upper() {
2     # Usage: upper "string"
3     printf '%s\n' "${1^^}"
4 }

Example Usage:

1 $ upper "hello"
2 HELLO
3
4 $ upper "HeLlO"
5 HELLO
6
7 $ upper "HELLO"
8 HELLO

Trim quotes from a string

Example Function:

1 trim_quotes() {
2     # Usage: trim_quotes "string"
3     : "${1//\'}"
4     printf '%s\n' "${_//\"}"
5 }

Example Usage:

1 $ var="'Hello', \"World\""
2 $ trim_quotes "$var"
3 Hello, World

Strip all instances of pattern from string

Example Function:

1 strip_all() {
2     # Usage: strip_all "string" "pattern"
3     printf '%s\n' "${1//$2}"
4 }

Example Usage:

1 $ strip_all "The Quick Brown Fox" "[aeiou]"
2 Th Qck Brwn Fx
3
4 $ strip_all "The Quick Brown Fox" "[[:space:]]"
5 TheQuickBrownFox
6
7 $ strip_all "The Quick Brown Fox" "Quick "
8 The Brown Fox

Strip first occurrence of pattern from string

Example Function:

1 strip() {
2     # Usage: strip "string" "pattern"
3     printf '%s\n' "${1/$2}"
4 }

Example Usage:

1 $ strip "The Quick Brown Fox" "[aeiou]"
2 Th Quick Brown Fox
3
4 $ strip "The Quick Brown Fox" "[[:space:]]"
5 TheQuick Brown Fox

Strip pattern from start of string

Example Function:

1 lstrip() {
2     # Usage: lstrip "string" "pattern"
3     printf '%s\n' "${1##$2}"
4 }

Example Usage:

1 $ lstrip "The Quick Brown Fox" "The "
2 Quick Brown Fox

Strip pattern from end of string

Example Function:

1 rstrip() {
2     # Usage: rstrip "string" "pattern"
3     printf '%s\n' "${1%%$2}"
4 }

Example Usage:

1 $ rstrip "The Quick Brown Fox" " Fox"
2 The Quick Brown

Check if string contains a sub-string

Using a test:

 1 if [[ "$var" == *sub_string* ]]; then
 2     printf '%s\n' "sub_string is in var."
 3 fi
 4
 5 # Inverse (substring not in string).
 6 if [[ "$var" != *sub_string* ]]; then
 7     printf '%s\n' "sub_string is not in var."
 8 fi
 9
10 # This works for arrays too!
11 if [[ "${arr[*]}" == *sub_string* ]]; then
12     printf '%s\n' "sub_string is in array."
13 fi

Using a case statement:

 1 case "$var" in
 2     *sub_string*)
 3         # Do stuff
 4     ;;
 5
 6     *sub_string2*)
 7         # Do more stuff
 8     ;;
 9
10     *)
11         # Else
12     ;;
13 esac

Check if string starts with sub-string

1 if [[ "$var" == sub_string* ]]; then
2     printf '%s\n' "var starts with sub_string."
3 fi
4
5 # Inverse (var does not start with sub_string).
6 if [[ "$var" != sub_string* ]]; then
7     printf '%s\n' "var does not start with sub_string."
8 fi

Check if string ends with sub-string

1 if [[ "$var" == *sub_string ]]; then
2     printf '%s\n' "var ends with sub_string."
3 fi
4
5 # Inverse (var does not start with sub_string).
6 if [[ "$var" != *sub_string ]]; then
7     printf '%s\n' "var does not end with sub_string."
8 fi

ARRAYS

Reverse an array

Enabling extdebug allows access to the BASH_ARGV array which stores the current function’s arguments in reverse.

Example Function:

1 reverse_array() {
2     # Usage: reverse_array "array"
3     shopt -s extdebug
4     f()(printf '%s\n' "${BASH_ARGV[@]}"); f "$@"
5     shopt -u extdebug
6 }

Example Usage:

 1 $ reverse_array 1 2 3 4 5
 2 5
 3 4
 4 3
 5 2
 6 1
 7
 8 $ arr=(red blue green)
 9 $ reverse_array "${arr[@]}"
10 green
11 blue
12 red

Remove duplicate array elements

Create a temporary associative array. When setting associative array values and a duplicate assignment occurs, bash overwrites the key. This allows us to effectively remove array duplicates.

CAVEAT: Requires bash 4+

Example Function:

 1 remove_array_dups() {
 2     # Usage: remove_array_dups "array"
 3     declare -A tmp_array
 4
 5     for i in "$@"; do
 6         [[ "$i" ]] && IFS=" " tmp_array["${i:- }"]=1
 7     done
 8
 9     printf '%s\n' "${!tmp_array[@]}"
10 }

Example Usage:

 1 $ remove_array_dups 1 1 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
 2 1
 3 2
 4 3
 5 4
 6 5
 7
 8 $ arr=(red red green blue blue)
 9 $ remove_array_dups "${arr[@]}"
10 red
11 green
12 blue

Random array element

Example Function:

1 random_array_element() {
2     # Usage: random_array_element "array"
3     local arr=("$@")
4     printf '%s\n' "${arr[RANDOM % $#]}"
5 }

Example Usage:

1 $ array=(red green blue yellow brown)
2 $ random_array_element "${array[@]}"
3 yellow
4
5 # Multiple arguments can also be passed.
6 $ random_array_element 1 2 3 4 5 6 7
7 3

Cycle through an array

Each time the printf is called, the next array element is printed. When the print hits the last array element it starts from the first element again.

1 arr=(a b c d)
2
3 cycle() {
4     printf '%s ' "${arr[${i:=0}]}"
5     ((i=i>=${#arr[@]}-1?0:++i))
6 }

Toggle between two values

This works the same as above, this is just a different use case.

1 arr=(true false)
2
3 cycle() {
4     printf '%s ' "${arr[${i:=0}]}"
5     ((i=i>=${#arr[@]}-1?0:++i))
6 }

LOOPS

Loop over a range of numbers

Alternative to seq.

1 # Loop from 0-100 (no variable support).
2 for i in {0..100}; do
3     printf '%s\n' "$i"
4 done

Loop over a variable range of numbers

Alternative to seq.

1 # Loop from 0-VAR.
2 VAR=50
3 for ((i=0;i<=VAR;i++)); do
4     printf '%s\n' "$i"
5 done

Loop over an array

1 arr=(apples oranges tomatoes)
2
3 # Just elements.
4 for element in "${arr[@]}"; do
5     printf '%s\n' "$element"
6 done

Loop over an array with an index

 1 arr=(apples oranges tomatoes)
 2
 3 # Elements and index.
 4 for i in "${!arr[@]}"; do
 5     printf '%s\n' "${arr[$i]}"
 6 done
 7
 8 # Alternative method.
 9 for ((i=0;i<${#arr[@]};i++)); do
10     printf '%s\n' "${arr[$i]}"
11 done

Loop over the contents of a file

1 while read -r line; do
2     printf '%s\n' "$line"
3 done < "file"

Loop over files and directories

Don’t use ls.

 1 # Greedy example.
 2 for file in *; do
 3     printf '%s\n' "$file"
 4 done
 5
 6 # PNG files in dir.
 7 for file in ~/Pictures/*.png; do
 8     printf '%s\n' "$file"
 9 done
10
11 # Iterate over directories.
12 for dir in ~/Downloads/*/; do
13     printf '%s\n' "$dir"
14 done
15
16 # Brace Expansion.
17 for file in /path/to/parentdir/{file1,file2,subdir/file3}; do
18     printf '%s\n' "$file"
19 done
20
21 # Iterate recursively.
22 shopt -s globstar
23 for file in ~/Pictures/**/*; do
24     printf '%s\n' "$file"
25 done
26 shopt -u globstar

FILE HANDLING

CAVEAT: bash does not handle binary data properly in versions < 4.4.

Read a file to a string

Alternative to the cat command.

1 file_data="$(<"file")"

Read a file to an array (by line)

Alternative to the cat command.

1 # Bash <4
2 IFS=$'\n' read -d "" -ra file_data < "file"
3
4 # Bash 4+
5 mapfile -t file_data < "file"

Get the first N lines of a file

Alternative to the head command.

CAVEAT: Requires bash 4+

Example Function:

1 head() {
2     # Usage: head "n" "file"
3     mapfile -tn "$1" line < "$2"
4     printf '%s\n' "${line[@]}"
5 }

Example Usage:

1 $ head 2 ~/.bashrc
2 # Prompt
3 PS1='➜ '
4
5 $ head 1 ~/.bashrc
6 # Prompt

Get the last N lines of a file

Alternative to the tail command.

CAVEAT: Requires bash 4+

Example Function:

1 tail() {
2     # Usage: tail "n" "file"
3     mapfile -tn 0 line < "$2"
4     printf '%s\n' "${line[@]: -$1}"
5 }

Example Usage:

1 $ tail 2 ~/.bashrc
2 # Enable tmux.
3 # [[ -z "$TMUX"  ]] && exec tmux
4
5 $ tail 1 ~/.bashrc
6 # [[ -z "$TMUX"  ]] && exec tmux

Get the number of lines in a file

Alternative to wc -l.

Example Function (bash 4):

1 lines() {
2     # Usage: lines "file"
3     mapfile -tn 0 lines < "$1"
4     printf '%s\n' "${#lines[@]}"
5 }

Example Function (bash 3):

This method uses less memory than the mapfile method and works in bash 3 but it is slower for bigger files.

1 lines_loop() {
2     # Usage: lines_loop "file"
3     count=0
4     while IFS= read -r _; do
5         ((count++))
6     done < "$1"
7     printf '%s\n' "$count"
8 }

Example Usage:

1 $ lines ~/.bashrc
2 48
3
4 $ lines_loop ~/.bashrc
5 48

Count files or directories in directory

This works by passing the output of the glob to the function and then counting the number of arguments.

Example Function:

1 count() {
2     # Usage: count /path/to/dir/*
3     #        count /path/to/dir/*/
4     printf '%s\n' "$#"
5 }

Example Usage:

 1 # Count all files in dir.
 2 $ count ~/Downloads/*
 3 232
 4
 5 # Count all dirs in dir.
 6 $ count ~/Downloads/*/
 7 45
 8
 9 # Count all jpg files in dir.
10 $ count ~/Pictures/*.jpg
11 64

Create an empty file

Alternative to touch.

1 # Shortest.
2 >file
3
4 # Longer alternatives:
5 :>file
6 echo -n >file
7 printf '' >file

Extract lines between two markers

Example Function:

 1 extract() {
 2     # Usage: extract file "opening marker" "closing marker"
 3     while IFS=$'\n' read -r line; do
 4         [[ "$extract" && "$line" != "$3" ]] && \
 5             printf '%s\n' "$line"
 6
 7         [[ "$line" == "$2" ]] && extract=1
 8         [[ "$line" == "$3" ]] && extract=
 9     done < "$1"
10 }

Example Usage:

1 # Extract code blocks from MarkDown file.
2 $ extract ~/projects/pure-bash/README.md '```sh' '```'
3 # Output here...

FILE PATHS

Get the directory name of a file path

Alternative to the dirname command.

Example Function:

1 dirname() {
2     # Usage: dirname "path"
3     printf '%s\n' "${1%/*}/"
4 }

Example Usage:

1 $ dirname ~/Pictures/Wallpapers/1.jpg
2 /home/black/Pictures/Wallpapers/
3
4 $ dirname ~/Pictures/Downloads/
5 /home/black/Pictures/

Get the base-name of a file path

Alternative to the basename command.

Example Function:

1 basename() {
2     # Usage: basename "path"
3     : "${1%/}"
4     printf '%s\n' "${_##*/}"
5 }

Example Usage:

1 $ basename ~/Pictures/Wallpapers/1.jpg
2 1.jpg
3
4 $ basename ~/Pictures/Downloads/
5 Downloads

VARIABLES

Assign and access a variable using a variable

1 hello_world="test"
2
3 # Create the variable name.
4 var1="world"
5 var2="hello_${var1}"
6
7 # Print the value of the variable name stored in 'hello_$var1'.
8 printf '%s\n' "${!var2}"

ESCAPE SEQUENCES

Contrary to popular belief, there is no issue in utilizing raw escape sequences. Using tput abstracts the same ANSI sequences as if printed manually. Worse still, tput is not actually portable. There are a number of tput variants each with different commands and syntaxes (try tput setaf 3 on a FreeBSD system). Raw sequences are fine.

Text Colors

NOTE: Sequences requiring RGB values only work in True-Color Terminal Emulators.

Sequence | What does it do? | Value
\e[38;5;<NUM>m | Set text foreground color. | 0-255
\e[48;5;<NUM>m | Set text background color. | 0-255
\e[38;2;<R>;<G>;<B>m | Set text foreground color to RGB color. | R, G, B
\e[48;2;<R>;<G>;<B>m | Set text background color to RGB color. | R, G, B

Text Attributes

Sequence | What does it do?
\e[m | Reset text formatting and colors.
\e[1m | Bold text.
\e[2m | Faint text.
\e[3m | Italic text.
\e[4m | Underline text.
\e[5m | Slow blink.
\e[7m | Swap foreground and background colors.

Cursor Movement

Sequence | What does it do? | Value
\e[<LINE>;<COLUMN>H | Move cursor to absolute position. | line, column
\e[H | Move cursor to home position (0,0). |
\e[<NUM>A | Move cursor up N lines. | num
\e[<NUM>B | Move cursor down N lines. | num
\e[<NUM>C | Move cursor right N columns. | num
\e[<NUM>D | Move cursor left N columns. | num
\e[s | Save cursor position. |
\e[u | Restore cursor position. |

Erasing Text

Sequence | What does it do?
\e[K | Erase from cursor position to end of line.
\e[1K | Erase from cursor position to start of line.
\e[2K | Erase the entire current line.
\e[J | Erase from the current line to the bottom of the screen.
\e[1J | Erase from the current line to the top of the screen.
\e[2J | Clear the screen.
\e[2J\e[H | Clear the screen and move cursor to 0,0.

PARAMETER EXPANSION

Indirection

Parameter | What does it do?
${!VAR} | Access a variable based on the value of VAR.
${!VAR*} | Expand to IFS separated list of variable names starting with VAR.
${!VAR@} | Expand to IFS separated list of variable names starting with VAR.

Replacement

Parameter | What does it do?
${VAR#PATTERN} | Remove shortest match of pattern from start of string.
${VAR##PATTERN} | Remove longest match of pattern from start of string.
${VAR%PATTERN} | Remove shortest match of pattern from end of string.
${VAR%%PATTERN} | Remove longest match of pattern from end of string.
${VAR/PATTERN/REPLACE} | Replace first match with string.
${VAR//PATTERN/REPLACE} | Replace all matches with string.
${VAR/PATTERN} | Remove first match.
${VAR//PATTERN} | Remove all matches.

Length

Parameter | What does it do?
${#VAR} | Length of var in characters.
${#ARR[@]} | Length of array in elements.

Expansion

Parameter | What does it do? |
${VAR:OFFSET} | Remove first N chars from variable. |
${VAR:OFFSET:LENGTH} | Get substring from N character to N character. <br> (${VAR:10:10}: Get sub-string from char 10 to char 20) |
${VAR:: OFFSET} | Get first N chars from variable. |
${VAR:: -OFFSET} | Remove last N chars from variable. |
${VAR: -OFFSET} | Get last N chars from variable. |
${VAR:OFFSET:-OFFSET} | Cut first N chars and last N chars. | bash 4.2+

Case Modification

Parameter | What does it do? | CAVEAT
${VAR^} | Uppercase first character. | bash 4+
${VAR^^} | Uppercase all characters. | bash 4+
${VAR,} | Lowercase first character. | bash 4+
${VAR,,} | Lowercase all characters. | bash 4+

Default Value

Parameter | What does it do?
${VAR:-STRING} | If VAR is empty or unset, use STRING as its value.
${VAR-STRING} | If VAR is unset, use STRING as its value.
${VAR:=STRING} | If VAR is empty or unset, set the value of VAR to STRING.
${VAR=STRING} | If VAR is unset, set the value of VAR to STRING.
${VAR:+STRING} | If VAR is not empty, use STRING as its value.
${VAR+STRING} | If VAR is set, use STRING as its value.
${VAR:?STRING} | Display an error if empty or unset.
${VAR?STRING} | Display an error if unset.

BRACE EXPANSION

Ranges

 1 # Syntax: {<START>..<END>}
 2
 3 # Print numbers 1-100.
 4 echo {1..100}
 5
 6 # Print range of floats.
 7 echo 1.{1..9}
 8
 9 # Print chars a-z.
10 echo {a..z}
11 echo {A..Z}
12
13 # Nesting.
14 echo {A..Z}{0..9}
15
16 # Print zero-padded numbers.
17 # CAVEAT: bash 4+
18 echo {01..100}
19
20 # Change increment amount.
21 # Syntax: {<START>..<END>..<INCREMENT>}
22 # CAVEAT: bash 4+
23 echo {1..10..2} # Increment by 2.

String Lists

1 echo {apples,oranges,pears,grapes}
2
3 # Example Usage:
4 # Remove dirs Movies, Music and ISOS from ~/Downloads/.
5 rm -rf ~/Downloads/{Movies,Music,ISOS}

ARITHMETIC OPERATORS

Assignment

Operators | What does it do?
= | Initialize or change the value of a variable.

Arithmetic

Operators | What does it do?
+ | Addition
- | Subtraction
* | Multiplication
/ | Division
** | Exponentiation
% | Modulo
+= | Plus-Equal (Increment a variable.)
-= | Minus-Equal (Decrement a variable.)
*= | Times-Equal (Multiply a variable.)
/= | Slash-Equal (Divide a variable.)
%= | Mod-Equal (Remainder of dividing a variable.)

Bitwise

Operators | What does it do?
<< | Bitwise Left Shift
<<= | Left-Shift-Equal
>> | Bitwise Right Shift
>>= | Right-Shift-Equal
& | Bitwise AND
&= | Bitwise AND-Equal
\| | Bitwise OR
\|= | Bitwise OR-Equal
~ | Bitwise NOT
^ | Bitwise XOR
^= | Bitwise XOR-Equal

Logical

Operators | What does it do?
! | NOT
&& | AND
\|\| | OR

Miscellaneous

Operators | What does it do? | Example
, | Comma Separator | ((a=1,b=2,c=3))

ARITHMETIC

Simpler syntax to set variables

 1 # Simple math
 2 ((var=1+2))
 3
 4 # Decrement/Increment variable
 5 ((var++))
 6 ((var--))
 7 ((var+=1))
 8 ((var-=1))
 9
10 # Using variables
11 ((var=var2*arr[2]))

Ternary Tests

1 # Set the value of var to var2 if var2 is greater than var.
2 # var: variable to set.
3 # var2>var: Condition to test.
4 # ?var2: If the test succeeds.
5 # :var: If the test fails.
6 ((var=var2>var?var2:var))

TRAPS

Traps allow a script to execute code on various signals. In pxltrm (a pixel art editor written in bash) traps are used to redraw the user interface on window resize. Another use case is cleaning up temporary files on script exit.

Traps should be added near the start of scripts so any early errors are also caught.

NOTE: For a full list of signals, see trap -l.

Do something on script exit

1 # Clear screen on script exit.
2 trap 'printf \\e[2J\\e[H\\e[m' EXIT

Ignore terminal interrupt (CTRL+C, SIGINT)

1 trap '' INT

React to window resize.

1 # Call a function on window resize.
2 trap 'code_here' SIGWINCH

Do something before every command.

1 trap 'code_here' DEBUG

Do something when a shell function or a sourced file finishes executing

1 trap 'code_here' RETURN

PERFORMANCE

Disable Unicode

If unicode is not required, it can be disabled for a performance increase. Results may vary however there have been noticeable improvements in neofetch and other programs.

1 # Disable unicode.
2 LC_ALL=C
3 LANG=C

OBSOLETE SYNTAX

Shebang

Use #!/usr/bin/env bash instead of #!/bin/bash.

The former searches the user’s PATH to find the bash binary.

The latter assumes it is always installed to /bin/ which can cause issues.

1 # Right:
2
3     #!/usr/bin/env bash
4
5 # Wrong:
6
7     #!/bin/bash

Command Substitution

Use $() instead of ` `.

1 # Right.
2 var="$(command)"
3
4 # Wrong.
5 var=`command`
6
7 # $() can easily be nested whereas `` cannot.
8 var="$(command "$(command)")"

Function Declaration

Do not use the function keyword, it reduces compatibility with older versions of bash.

1 # Right.
2 do_something() {
3     # ...
4 }
5
6 # Wrong.
7 function do_something() {
8     # ...
9 }

INTERNAL VARIABLES

Get the location to the bash binary

1 "$BASH"

Get the version of the current running bash process

1 # As a string.
2 "$BASH_VERSION"
3
4 # As an array.
5 "${BASH_VERSINFO[@]}"

Open the user’s preferred text editor

1 "$EDITOR" "$file"
2
3 # NOTE: This variable may be empty, set a fallback value.
4 "${EDITOR:-vi}" "$file"

Get the name of the current function

 1 # Current function.
 2 "${FUNCNAME[0]}"
 3
 4 # Parent function.
 5 "${FUNCNAME[1]}"
 6
 7 # So on and so forth.
 8 "${FUNCNAME[2]}"
 9 "${FUNCNAME[3]}"
10
11 # All functions including parents.
12 "${FUNCNAME[@]}"

Get the host-name of the system

1 "$HOSTNAME"
2
3 # NOTE: This variable may be empty.
4 # Optionally set a fallback to the hostname command.
5 "${HOSTNAME:-$(hostname)}"

Get the architecture of the Operating System

1 "$HOSTTYPE"

Get the name of the Operating System / Kernel

This can be used to add conditional support for different Operating Systems without needing to call uname.

1 "$OSTYPE"

Get the current working directory

This is an alternative to the pwd built-in.

1 "$PWD"

Get the number of seconds the script has been running

1 "$SECONDS"

Get a pseudorandom integer

Each time $RANDOM is used, a different integer between 0 and 32767 is returned. This variable should not be used for anything related to security (this includes encryption keys etc).

1 "$RANDOM"

INFORMATION ABOUT THE TERMINAL

Get the terminal size in lines and columns (from a script)

This is handy when writing scripts in pure bash and stty/tput can’t be called.

Example Function:

1 get_term_size() {
2     # Usage: get_term_size
3
4     # (:;:) is a micro sleep to ensure the variables are
5     # exported immediately.
6     shopt -s checkwinsize; (:;:)
7     printf '%s\n' "$LINES $COLUMNS"
8 }

Example Usage:

1 # Output: LINES COLUMNS
2 $ get_term_size
3 15 55

Get the terminal size in pixels

CAVEAT: This does not work in some terminal emulators.

Example Function:

1 get_window_size() {
2     # Usage: get_window_size
3     printf '%b' "${TMUX:+\\ePtmux;\\e}\\e[14t${TMUX:+\\e\\\\}"
4     IFS=';t' read -d t -t 0.05 -sra term_size
5     printf '%s\n' "${term_size[1]}x${term_size[2]}"
6 }

Example Usage:

1 # Output: WIDTHxHEIGHT
2 $ get_window_size
3 1200x800
4
5 # Output (fail):
6 $ get_window_size
7 x

Get the current cursor position

This is useful when creating a TUI in pure bash.

Example Function:

1 get_cursor_pos() {
2     # Usage: get_cursor_pos
3     IFS='[;' read -p $'\e[6n' -d R -rs _ y x _
4     printf '%s\n' "$x $y"
5 }

Example Usage:

1 # Output: X Y
2 $ get_cursor_pos
3 1 8

CONVERSION

Convert a hex color to RGB

Example Function:

1 hex_to_rgb() {
2     # Usage: hex_to_rgb "#FFFFFF"
3     ((r=16#${1:1:2}))
4     ((g=16#${1:3:2}))
5     ((b=16#${1:5:6}))
6
7     printf '%s\n' "$r $g $b"
8 }

Example Usage:

1 $ hex_to_rgb "#FFFFFF"
2 255 255 255

Convert an RGB color to hex

Example Function:

1 rgb_to_hex() {
2     # Usage: rgb_to_hex "r" "g" "b"
3     printf '#%02x%02x%02x\n' "$1" "$2" "$3"
4 }

Example Usage:

1 $ rgb_to_hex "255" "255" "255"
2 #FFFFFF

CODE GOLF

Shorter for loop syntax

 1 # Tiny C Style.
 2 for((;i++<10;)){ echo "$i";}
 3
 4 # Undocumented method.
 5 for i in {1..10};{ echo "$i";}
 6
 7 # Expansion.
 8 for i in {1..10}; do echo "$i"; done
 9
10 # C Style.
11 for((i=0;i<=10;i++)); do echo "$i"; done

Shorter infinite loops

1 # Normal method
2 while :; do echo hi; done
3
4 # Shorter
5 for((;;)){ echo hi;}

Shorter function declaration

 1 # Normal method
 2 f(){ echo hi;}
 3
 4 # Using a subshell
 5 f()(echo hi)
 6
 7 # Using arithmetic
 8 # This can be used to assign integer values.
 9 # Example: f a=1
10 #          f a++
11 f()(($1))
12
13 # Using tests, loops etc.
14 # NOTE: ‘while’, ‘until’, ‘case’, ‘(())’, ‘[[]]’ can also be used.
15 f()if true; then echo "$1"; fi
16 f()for i in "$@"; do echo "$i"; done

Shorter if syntax

 1 # One line
 2 # Note: The 3rd statement may run when the 1st is true
 3 [[ "$var" == hello ]] && echo hi || echo bye
 4 [[ "$var" == hello ]] && { echo hi; echo there; } || echo bye
 5
 6 # Multi line (no else, single statement)
 7 # Note: The exit status may not be the same as with an if statement
 8 [[ "$var" == hello ]] && \
 9     echo hi
10
11 # Multi line (no else)
12 [[ "$var" == hello ]] && {
13     echo hi
14     # ...
15 }

Simpler case statement to set variable

The : built-in can be used to avoid repeating variable= in a case statement. The $_ variable stores the last argument of the last command. : always succeeds so it can be used to store the variable value.

 1 # Modified snippet from Neofetch.
 2 case "$OSTYPE" in
 3     "darwin"*)
 4         : "MacOS"
 5     ;;
 6
 7     "linux"*)
 8         : "Linux"
 9     ;;
10
11     *"bsd"* | "dragonfly" | "bitrig")
12         : "BSD"
13     ;;
14
15     "cygwin" | "msys" | "win32")
16         : "Windows"
17     ;;
18
19     *)
20         printf '%s\n' "Unknown OS detected, aborting..." >&2
21         exit 1
22     ;;
23 esac
24
25 # Finally, set the variable.
26 os="$_"

OTHER

Use read as an alternative to the sleep command

Surprisingly, sleep is an external command and not a bash built-in.

CAVEAT: Requires bash 4+

Example Function:

1 read_sleep() {
2     # Usage: sleep 1
3     #        sleep 0.2
4     read -rst "${1:-1}" -N 999
5 }

Example Usage:

1 read_sleep 1
2 read_sleep 0.1
3 read_sleep 30

Check if a program is in the user’s PATH

 1 # There are 3 ways to do this and either one can be used.
 2 type -p executable_name &>/dev/null
 3 hash executable_name &>/dev/null
 4 command -v executable_name &>/dev/null
 5
 6 # As a test.
 7 if type -p executable_name &>/dev/null; then
 8     # Program is in PATH.
 9 fi
10
11 # Inverse.
12 if ! type -p executable_name &>/dev/null; then
13     # Program is not in PATH.
14 fi
15
16 # Example (Exit early if program is not installed).
17 if ! type -p convert &>/dev/null; then
18     printf '%s\n' "error: convert is not installed, exiting..."
19     exit 1
20 fi

Get the current date using strftime

Bash’s printf has a built-in method of getting the date which can be used in place of the date command.

CAVEAT: Requires bash 4+

Example Function:

1 date() {
2     # Usage: date "format"
3     # See: 'man strftime' for format.
4     printf "%($1)T\\n" "-1"
5 }

Example Usage:

 1 # Using above function.
 2 $ date "%a %d %b  - %l:%M %p"
 3 Fri 15 Jun  - 10:00 AM
 4
 5 # Using printf directly.
 6 $ printf '%(%a %d %b  - %l:%M %p)T\n' "-1"
 7 Fri 15 Jun  - 10:00 AM
 8
 9 # Assigning a variable using printf.
10 $ printf -v date '%(%a %d %b  - %l:%M %p)T\n' '-1'
11 $ printf '%s\n' "$date"
12 Fri 15 Jun  - 10:00 AM

Generate a UUID V4

Example Function:

 1 uuid() {
 2     # Usage: uuid
 3     C="89ab"
 4
 5     for ((N=0;N<16;++N)); do
 6         B="$((RANDOM%256))"
 7
 8         case "$N" in
 9             6)  printf '4%x' "$((B%16))" ;;
10             8)  printf '%c%x' "${C:$RANDOM%${#C}:1}" "$((B%16))" ;;
11
12             3|5|7|9)
13                 printf '%02x-' "$B"
14             ;;
15
16             *)
17                 printf '%02x' "$B"
18             ;;
19         esac
20     done
21
22     printf '\n'
23 }

Example Usage:

1 $ uuid
2 d5b6c731-1310-4c24-9fe3-55d556d44374

Progress bars

This is a simple way of drawing progress bars without needing a for loop in the function itself.

Example Function:

 1 bar() {
 2     # Usage: bar 1 10
 3     #            ^----- Elapsed Percentage (0-100).
 4     #               ^-- Total length in chars.
 5     ((elapsed=$1*$2/100))
 6
 7     # Create the bar with spaces.
 8     printf -v prog  "%${elapsed}s"
 9     printf -v total "%$(($2-elapsed))s"
10
11     printf '%s\r' "[${prog// /-}${total}]"
12 }

Example Usage:

1 for ((i=0;i<=100;i++)); do
2     # Pure bash micro sleeps (for the example).
3     (:;:) && (:;:) && (:;:) && (:;:) && (:;:)
4
5     # Print the bar.
6     bar "$i" "10"
7 done
8
9 printf '\n'

Get the list of functions in a script

1 get_functions() {
2     # Usage: get_functions
3     IFS=$'\n' read -d "" -ra functions < <(declare -F)
4     printf '%s\n' "${functions[@]//declare -f }"
5 }

Bypass shell aliases

1 # alias
2 ls
3
4 # command
5 # shellcheck disable=SC1001
6 \ls

Bypass shell functions

1 # function
2 ls
3
4 # command
5 command ls