Skip to content

Bash Scripting Github

The Bourne - Again Shell

Bash Scripting.
- Category: CLI
- tags: [Featured]
- Keywords:
 - Variables:
    - Functions
    - Interpolation
    - Brace expansions
    - Loops
    - Conditional execution
    - Command substitution

Getting Started⚓︎

Introduction⚓︎

This is a quick reference to getting started with Bash scripting.

Example⚓︎

Example

#!/usr/bin/env bash

name="John"
echo "Hello $name!"

Variables⚓︎

Variables

name="John"
echo $name  # see below
echo "$name"
echo "${name}!"

Generally Quote Variables

  • Generally Quote Your Variables Unless They Contain Wildcards to Expand or Command Fragments.
wildcard="*.txt"
options="iv"
cp -$options $wildcard /tmp

String Quotes

name="John"
echo "Hi $name"  #=> Hi John
echo 'Hi $name'  #=> Hi $name

Shell Execution

echo "I'm in $(pwd)"
echo "I'm in `pwd`"  # obsolescent
# Same

Conditional Execution

Conditional Execution⚓︎

git commit && git push
git commit || echo "Commit failed"
  • Conditional Execution
    A sequence of one or more pipelines separated by one of the operators.
    Go to GNU Bash Manual

  • MaterialX Start Page
    Go back to the project's (static site) main landing page, Getting Started
    Return to Start Page

  • MkDocs ➻ MaterialX
    Go back to the root Afridyne Systems™ ➠ MkDocs ➻ MaterialX documentation.
    Return to MaterialX

Functions

Functions⚓︎

get_name() {
  echo "John"
}

echo "You are $(get_name)"
  • Shell Functions
    Official documentation for defining and executing named command groups.
    Go to GNU Bash Manual

  • Command Substitution
    Command substitution allows the output of a command to replace the command itself.
    Go to GNU Bash Manual

  • MkDocs ➻ MaterialX
    Go back to the root Afridyne Systems™ ➠ MkDocs ➻ MaterialX documentation.
    Return to MaterialX

Conditionals

Conditionals⚓︎

if [[ -z "$string" ]]; then
  echo "String is empty"
elif [[ -n "$string" ]]; then
  echo "String is not empty"
fi

Strict Mode

Strict Mode⚓︎

set -euo pipefail
IFS=$'\n\t'

Brace Expansion

Brace Expansion⚓︎

echo {A,B}.js
Expression Description
{A,B} Same as A B
{A,B}.js Same as A.js B.js
{1..5} Same as 1 2 3 4 5
{{1..3},{7..9}} Same as 1 2 3 7 8 9

Parameter Expansion

Parameter Expansion⚓︎

Basics⚓︎

name="John"
echo "${name}"
echo "${name/J/j}"    #=> "john" (substitution)
echo "${name:0:2}"    #=> "Jo" (slicing)
echo "${name::2}"     #=> "Jo" (slicing)
echo "${name::-1}"    #=> "Joh" (slicing)
echo "${name:(-1)}"   #=> "n" (slicing from right)
echo "${name:(-2):1}" #=> "h" (slicing from right)
echo "${food:-Cake}"  #=> $food or "Cake"
length=2
echo "${name:0:length}"  #=> "Jo"

Path & String Manipulation

Path & String Manipulation⚓︎

str="/path/to/foo.cpp"
echo "${str%.cpp}"    # /path/to/foo
echo "${str%.cpp}.o"  # /path/to/foo.o
echo "${str%/*}"      # /path/to

echo "${str##*.}"     # cpp (extension)
echo "${str##*/}"     # foo.cpp (basepath)

echo "${str#*/}"      # path/to/foo.cpp
echo "${str##*/}"     # foo.cpp

echo "${str/foo/bar}" # /path/to/bar.cpp

Slicing & Extraction

Slicing & Extraction⚓︎

str="Hello world"
echo "${str:6:5}"    # "world"
echo "${str: -5:5}"  # "world"
src="/path/to/foo.cpp"
base=${src##*/}   #=> "foo.cpp" (basepath)
dir=${src%$base}  #=> "/path/to/" (dirpath)

Expansion & Indirection

Prefix Name Expansion & Indirection⚓︎

# Prefix Name Expansion
prefix_a=one
prefix_b=two
echo ${!prefix_*}  # prefix_a prefix_b

# Indirection
name=joe
pointer=name
echo ${!pointer}   # joe
  • Parameter Expansion
    GNU Bash Man. Core func of bash is to manage parameters.
    Go to GNU Bash Manual

  • Bash-Hackers Wiki
    Detailed community guide on Parameter Expansion.
    Go to Archive

  • Expansion Overview
    General documentation on all Bash expansion types.
    Go to Expansions

Substitution⚓︎

Code Description
${foo%suffix} Remove: ⤞⟶ suffix
${foo#prefix} Remove: ⤞⟶ prefix
Code Description
${foo%%suffix} Remove long suffix
${foo/%suffix} Remove long suffix
${foo##prefix} Remove long prefix
${foo/#prefix} Remove long prefix
Code Description
${foo/from/to} Replace / first match
${foo//from/to} Replace / all
Code Description
${foo/%from/to} Replace: ⟶ suffix
${foo/#from/to} Replace: ⟶ prefix

Comments

Comments⚓︎

# Single line comment
: '
This is a
multi line
comment
'

Substrings⚓︎

Expression Description
${foo:0:3} Substring (position, length)
${foo:(-3):3} Substring from the right

Substitution Length⚓︎

Expression Description
${#foo} Length of $foo

Manipulation⚓︎

Manipulation

str="HELLO WORLD!"
echo "${str,}"   #=> "hELLO WORLD!" (lowercase 1st letter)
echo "${str,,}"  #=> "hello world!" (all lowercase)

str="hello world!"
echo "${str^}"   #=> "Hello world!" (uppercase 1st letter)
echo "${str^^}"  #=> "HELLO WORLD!" (all uppercase)

Default Values⚓︎

Expression Description
${foo:-val} $foo, or val if unset (or null)
${foo:=val} Set $foo to val if unset (or null)
${foo:+val} val if $foo is set (and not null)
${foo:?message} Show error message and exit if $foo is unset (or null)

Omitting the : removes the (non)nullity checks, e.g. ${foo-val} expands to val if unset otherwise $foo.

Loops⚓︎

Basic For Loop

for i in /etc/rc.*; do
  echo "$i"
done

C-like For Loop

for ((i = 0 ; i < 100 ; i++)); do
  echo "$i"
done

Ranges

for i in {1..5}; do
    echo "Welcome $i"
done

With Step Size

for i in {5..50..5}; do
    echo "Welcome $i"
done

Reading Lines

while read -r line; do
  echo "$line"
done <file.txt

Forever

while true; do
  ···
done

Functions⚓︎

Defining Functions

myfunc() {
    echo "hello $1"
}
# Same as above (alternate syntax)
function myfunc {
    echo "hello $1"
}
myfunc "John"

Returning Values

Returning Values⚓︎

myfunc() {
    local myresult='some value'
    echo "$myresult"
}
result=$(myfunc)

Raising Errors

Raising Errors⚓︎

myfunc() {
  return 1
}
if myfunc; then
  echo "success"
else
  echo "failure"
fi

Arguments⚓︎

Expression Description
$# Number of arguments
$* All positional arguments (as a single word)
$@ All positional arguments (as separate strings)
$1 First argument
$_ Last argument of the previous command

Note: $@ and $* must be quoted in order to perform as described. Otherwise, they do exactly the same thing (arguments as separate strings).

See Special Parameters.

Conditionals⚓︎

Conditions

Conditions⚓︎

Note that [[ is actually a command/program that returns either 0 (true) or 1 (false). Any program that obeys the same logic (like all base utils, such as grep(1) or ping(1)) can be used as condition, see examples.

Condition Description
[[ -z STRING ]] Empty string
[[ -n STRING ]] Not empty string
[[ STRING == STRING ]] Equal
[[ STRING != STRING ]] Not Equal
[[ NUM -eq NUM ]] Equal
[[ NUM -ne NUM ]] Not equal
[[ NUM -lt NUM ]] Less than
[[ NUM -le NUM ]] Less than or equal
[[ NUM -gt NUM ]] Greater than
[[ NUM -ge NUM ]] Greater than or equal
[[ STRING =~ STRING ]] Regexp
(( NUM < NUM )) Numeric conditions

Conditions⚓︎

Condition Description
[[ -o noclobber ]] If OPTIONNAME is enabled
[[ ! EXPR ]] Not
[[ X && Y ]] And
[[ X || Y ]] Or

File conditions⚓︎

Condition Description
[[ -e FILE ]] Exists
[[ -r FILE ]] Readable
[[ -h FILE ]] Symlink
[[ -d FILE ]] Directory
[[ -w FILE ]] Writable
[[ -s FILE ]] Size is > 0 bytes
[[ -f FILE ]] File
[[ -x FILE ]] Executable
[[ FILE1 -nt FILE2 ]] 1 is more recent than 2
[[ FILE1 -ot FILE2 ]] 2 is more recent than 1
[[ FILE1 -ef FILE2 ]] Same files

Example

Example⚓︎

# String
if [[ -z "$string" ]]; then
  echo "String is empty"
elif [[ -n "$string" ]]; then
  echo "String is not empty"
else
  echo "This never happens"
fi
# Combinations
if [[ X && Y ]]; then
  ...
fi
# Equal
if [[ "$A" == "$B" ]]
# Regex
if [[ "A" =~ . ]]
if (( $a < $b )); then
   echo "$a is smaller than $b"
fi
if [[ -e "file.txt" ]]; then
  echo "file exists"
fi

Arrays⚓︎

Defining Arrays

Defining Arrays⚓︎

Fruits=('Apple' 'Banana' 'Orange')
Fruits[0]="Apple"
Fruits[1]="Banana"
Fruits[2]="Orange"

Working with arrays

Working with arrays⚓︎

echo "${Fruits[0]}"           # Element #0
echo "${Fruits[-1]}"          # Last element
echo "${Fruits[@]}"           # All elements, space-separated
echo "${#Fruits[@]}"          # Number of elements
echo "${#Fruits}"             # String length of the 1st element
echo "${#Fruits[3]}"          # String length of the Nth element
echo "${Fruits[@]:3:2}"       # Range (from position 3, length 2)
echo "${!Fruits[@]}"          # Keys of all elements, space-separated

Operations

Operations⚓︎

Fruits=("${Fruits[@]}" "Watermelon")    # Push
Fruits+=('Watermelon')                  # Also Push
Fruits=( "${Fruits[@]/Ap*/}" )          # Remove by regex match
unset Fruits[2]                         # Remove one item
Fruits=("${Fruits[@]}")                 # Duplicate
Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
words=($(< datafile))                   # From file (split by IFS)

Iteration

Iteration⚓︎

for i in "${arrayName[@]}"; do
  echo "$i"
done

Dictionaries⚓︎

Defining

Defining⚓︎

declare -A sounds
sounds[dog]="bark"
sounds[cow]="moo"
sounds[bird]="tweet"
sounds[wolf]="howl"

Declares sounds as a Dictionary object (aka associative array).

Working with dictionaries

Working with dictionaries⚓︎

echo "${sounds[dog]}" # Dog's sound
echo "${sounds[@]}"   # All values
echo "${!sounds[@]}"  # All keys
echo "${#sounds[@]}"  # Number of elements
unset sounds[dog]     # Delete dog

Iteration⚓︎

Iterate over values

Iterate over values⚓︎

for val in "${sounds[@]}"; do
  echo "$val"
done

Iterate over keys

Iterate over keys⚓︎

for key in "${!sounds[@]}"; do
  echo "$key"
done

Options⚓︎

Options

Options⚓︎

set -o noclobber  # Avoid overlay files (echo "hi" > foo)
set -o errexit    # Used to exit upon error, avoiding cascading errors
set -o pipefail   # Unveils hidden failures
set -o nounset    # Exposes unset variables

Glob options

Glob options⚓︎

shopt -s nullglob    # Non-matching globs are removed  ('*.foo' => '')
shopt -s failglob    # Non-matching globs throw errors
shopt -s nocaseglob  # Case insensitive globs
shopt -s dotglob     # Wildcards match dotfiles ("*.sh" => ".foo.sh")
shopt -s globstar    # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')

Set GLOBIGNORE as a colon-separated list of patterns to be removed from glob matches.

History⚓︎

Commands⚓︎

Command Description
history Show history
shopt -s histverify Don't execute expanded result immediately

Expansions⚓︎

Expression Description
!$ Expand last parameter of most recent command
!* Expand all parameters of most recent command
!-n Expand nth most recent command
!n Expand nth command in history
!<command> Expand most recent invocation of command <command>

Operations⚓︎

Code Description
!! Execute last command again
!!:s/<FROM>/<TO>/ Replace first occurrence of <FROM> to <TO> in most recent command
!!:gs/<FROM>/<TO>/ Replace all occurrences of <FROM> to <TO> in most recent command
!$:t Expand only basename from last parameter of most recent command
!$:h Expand only directory from last parameter of most recent command

!! and !$ can be replaced with any valid expansion.

Slices⚓︎

Code Description
!!:n Expand only nth token from most recent command (command is 0; first argument is 1)
!^ Expand first argument from most recent command
!$ Expand last token from most recent command
!!:n-m Expand range of tokens from most recent command
!!:n-$ Expand nth token to last from most recent command

!! can be replaced with any valid expansion i.e. !cat, !-2, !42, etc.

Miscellaneous⚓︎

Numeric calculations

Numeric calculations⚓︎

$((a + 200))      # Add 200 to $a
$(($RANDOM%200))  # Random number 0..199
declare -i count  # Declare as type integer
count+=1          # Increment

Subshells

Subshells⚓︎

(cd somedir; echo "I'm now in $PWD")
pwd # still in first directory

Redirection

Redirection⚓︎

python hello.py > output.txt            # stdout to (file)
python hello.py >> output.txt           # stdout to (file), append
python hello.py 2> error.log            # stderr to (file)
python hello.py 2>&1                    # stderr to stdout
python hello.py 2>/dev/null             # stderr to (null)
python hello.py >output.txt 2>&1        # stdout and stderr to (file), equivalent to &>
python hello.py &>/dev/null             # stdout and stderr to (null)
echo "$0: warning: too many users" >&2  # print diagnostic message to stderr
python hello.py < foo.txt      # feed foo.txt to stdin for python
diff <(ls -r) <(ls)            # Compare two stdout without files

Inspecting commands

Inspecting commands⚓︎

command -V cd
#=> "cd is a function/alias/whatever"

Trap errors

Trap errors⚓︎

trap 'echo Error at about $LINENO' ERR

or

traperr() {
  echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
}

set -o errtrace
trap traperr ERR

Case/switch

Case/switch⚓︎

case "$1" in
  start | up)
    vagrant up
    ;;

  *)
    echo "Usage: $0 {start|stop|ssh}"
    ;;
esac

Source relative

Source relative⚓︎

source "${0%/*}/../share/foo.sh"

printf

printf⚓︎

printf "Hello %s, I'm %s" Sven Olga
#=> "Hello Sven, I'm Olga

printf "1 + 1 = %d" 2
#=> "1 + 1 = 2"

printf "This is how you print a float: %f" 2
#=> "This is how you print a float: 2.000000"

printf '%s\n' '#!/bin/bash' 'echo hello' >file
# format string is applied to each group of arguments
printf '%i+%i=%i\n' 1 2 3  4 5 9

Transform strings⚓︎

Command option Description
-c Operations apply to characters not in the given set
-d Delete characters
-s Replaces repeated characters with single occurrence
-t Truncates
[:upper:] All upper case letters
[:lower:] All lower case letters
[:digit:] All digits
[:space:] All whitespace
[:alpha:] All letters
[:alnum:] All letters and digits

Example

Example⚓︎

echo "Welcome To Devhints" | tr '[:lower:]' '[:upper:]'
WELCOME TO DEVHINTS

Directory of script

Directory of script⚓︎

dir=${0%/*}

Getting options

Getting options⚓︎

while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
  -V | --version )
    echo "$version"
    exit
    ;;
  -s | --string )
    shift; string=$1
    ;;
  -f | --flag )
    flag=1
    ;;
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi

Heredoc

Heredoc⚓︎

cat <<END
hello world
END

Heredoc allows a section of your source code to be treated as a file.

Herestring

Herestring⚓︎

tr '[:lower:]' '[:upper:]' <<< "Will be uppercased, even $variable"

Herestring allows a string to be treated as a standard input (stdin).

Process substitution

Process substitution⚓︎

# loop on myfunc output lines
while read -r line; do
  echo "$line"
done < <(myfunc)

# compare content of two folders
diff <(ls "$dir1") <(ls "$dir2")

Process substitution allows the input (or output) of a command to be treated as a file.

Reading input

Reading input⚓︎

echo -n "Proceed? [y/n]: "
read -r ans
echo "$ans"

The -r option disables a peculiar legacy behavior with backslashes.

read -n 1 ans    # Just one character

Special Variables⚓︎

Expression Description
$? Exit status of last task
$! PID of last background task
$$ PID of shell
$0 Filename of the shell script
$_ Last argument of the previous command
${PIPESTATUS[n]} return value of piped commands (array)

Go to Previous Directory

Previous Directory⚓︎

pwd # /home/user/foo
cd bar/
pwd # /home/user/foo/bar
cd -
pwd # /home/user/foo

Check for Command's Result

Check Comd's Result⚓︎

if ping -c 1 google.com; then
  echo "It appears you have a working internet connection"
fi

Grep Check

Grep Check⚓︎

if grep -q 'foo' ~/.bash_history; then
  echo "You appear to have typed 'foo' in the past"
fi

Also See⚓︎

Table Reference: systemctl⚓︎
Action Command Note
Analyzing the system state
Show system status systemctl status
List running units systemctl or systemctl list-units
List failed units systemctl --failed
List installed unit files1 systemctl list-unit-files
Show process status for a PID systemctl status pid cgroup slice, memory and parent
Checking the unit status
Show a manual page associated with a unit systemctl help unit as supported by the unit
Status of a unit systemctl status unit including whether it is running or not
Check whether a unit is enabled systemctl is-enabled unit
Starting, restarting, reloading a unit
Start a unit immediately systemctl start unit as root
Stop a unit immediately systemctl stop unit as root
Restart a unit systemctl restart unit as root
Reload a unit and its configuration systemctl reload unit as root
Reload systemd manager configuration2 systemctl daemon-reload as root scan for new or changed units
Enabling a unit
Enable a unit to start automatically at boot systemctl enable unit as root
Enable a unit to start automatically at boot and start it immediately systemctl enable --now unit as root
Disable a unit to no longer start at boot systemctl disable unit as root
Reenable a unit3 systemctl reenable unit as root i.e. disable and enable anew
Masking a unit
Mask a unit to make it impossible to start4 systemctl mask unit as root
Unmask a unit systemctl unmask unit as root

Operators for Integer Comparison

Operator Description
-eq equal
-ne not equal
-gt greater than
-ge greater than or equal to
-lt less than
-le less than or equal to

Operators for String Comparison

Operator Description
== equal
!= not equal
> greater than
< less than
-n string is not null
-z string is null

Redirections⚓︎

But what if you'd want to save the results to a file? Bash has a redirect operator > that may be used to control where the output is delivered.

some_command > out.log            # Redirect stdout to out.log
some_command 2> err.log           # Redirect stderr to file err.log
some_command 2>&1                 # Redirect stderr to stdout
some_command 1>/dev/null 2>&1     # Silence both stdout and stderr

Complete summary:

Syntax StdOut visibility StdErr visibility StdOut in file StdErr in file existing file
> no yes yes no overwrite
>> no yes yes no append
2> yes no no yes overwrite
2>> yes no no yes append
&> no no yes yes overwrite
&>> no no yes yes append
tee yes yes yes no overwrite
tee -a yes yes yes no append
n.e. (*) yes yes no yes overwrite
n.e. (*) yes yes no yes append
\|& tee yes yes yes yes overwrite
\|& tee -a yes yes yes yes append

Formatting and linting⚓︎

It is important to keep the formatting of your script as consistent as possible. Beautysh is an amazing tool that helps you to format your script. To use it, just run the following command in a directory where your scripts are located:

beautysh **/*.sh

Additionally we advise to use shellcheck for code inspection.

shellcheck **/*.sh

Available scripts⚓︎

Intro⚓︎

# Description Code
1 Prints "Hello, world!" to the console. hello_world.sh
2 Demonstrates the use of if statements to check conditions. conditionals.sh
3 Shows the use of a while loop to repeatedly execute code. while_loop.sh
4 Demonstrates the use of a for loop to iterate over elements. for_loop.sh
5 Displays the digits of a given number, one digit per line. digits.sh
6 Prints all of the numbers within a specified range, one number per line. numbers_in_interval.sh
7 Prints a Christmas tree pattern to the console. christmas_tree.sh
8 Prompts the user for a response to a given question and stores their response in a variable. prompt_for_answer.sh

Math⚓︎

# Description Code
1 Performs basic arithmetic operations (addition, subtraction, multiplication, and division) on two numbers. arithmetic_operations.sh
2 Calculates the sum of all the arguments passed to it, treating them as numbers. sum_args.sh
3 Converts a number from the decimal (base 10) system to its equivalent in the binary (base 2) system. decimal_binary.sh
4 Calculates the factorial of a given integer. factorial.sh
5 Determines whether a given number is a prime number or not. is_prime.sh
6 Calculates the square root of a given number. sqrt.sh

Strings⚓︎

# Description Code
1 Counts the number of times a specific character appears in a given string. count_char.sh
2 Converts all uppercase letters in a given string to lowercase. lower.sh
3 Converts all lowercase letters in a given string to uppercase. upper.sh
4 Checks if a given string is a palindrome, i.e., a word that is spelled the same way forwards and backwards. is_palindrome.sh
5 Checks if two given strings are anagrams, i.e., if they are made up of the same letters rearranged in a different order. are_anagrams.sh
6 Calculates the Hamming Distance between two strings, i.e., the number of positions at which the corresponding characters are different. hamming_distance.sh
7 Sorts a given string alphabetically, considering all letters to be lowercase. sort_string.sh
8 Creates a word histogram. word_histogram.sh

Arrays⚓︎

# Description Code
1 Calculates the arithmetic mean of a given list of numbers. arith_mean.sh
2 Finds the maximum value in a given array of numbers. max_array.sh
3 Finds the minimum value in a given array of numbers. min_array.sh
4 Removes duplicates from a given array of numbers. remove_duplicates_in_array.sh

Files⚓︎

# Description Code
1 Counts the number of files in a specified directory. count_files.sh
2 Creates a new directory with a specified name. make_dir.sh
3 Counts the number of lines in a specified text file. line_counter.sh
4 Gets the middle line from a specified text file. middle_line.sh
5 Removes duplicate lines from a specified file. remove_duplicate_lines.sh
6 Replaces all forward slashes with backward slashes and vice versa in a specified file. switch_slashes.sh
7 Adds specified text to the beginning of a specified file. prepend_text_to_file.sh
8 Removes all lines in a specified file that contain only whitespaces. remove_empty_lines.sh
9 Renames all files in a specified directory with a particular extension to a new extension. rename_extension.sh
10 Strips digits from every string found in a given file. strip_digits.sh
11 Lists the most recently modified files in a given directory. recently_modified_files.sh

System administration⚓︎

# Description Code
1 Retrieves basic system information, such as hostname and kernel version. system_info.sh
2 Determines the type and version of the operating system running on the machine. check_os.sh
3 Checks whether the current user has root privileges. check_if_root.sh
4 Checks if the apt command, used for package management on Debian-based systems, is available on the machine. check_apt_avail.sh
5 Retrieves the size of the machine's random access memory (RAM). ram_memory.sh
6 Gets the current temperature of the machine's central processing unit (CPU). cpu_temp.sh
7 Retrieves the current overall CPU usage of the machine. cpu_usage.sh
8 Blocks certain websites from being visited on the local machine by modifying the hosts file. web_block.sh
9 Creates a backup of the system's files, compresses the backup, and encrypts the resulting archive for storage. backup.sh
10 Displays processes that are not being waited on by any parent process. Orphan processes are created when the parent process terminates. orphans.sh
11 Displays processes that are in an undead state, also known as a "zombie" state. Zombie processes have completed execution but remain in the process table. zombies.sh

Programming workflow⚓︎

# Description Code
1 Removes the carriage return character (\r) from the given files, which may be present in files transferred between systems with different line ending conventions. remove_carriage_return.sh
2 Replaces all characters with diacritical marks in the given files with their non-diacritical counterparts. Diacritical marks are small signs added above or below letters to indicate different pronunciations or tones in some languages. remove_diacritics.sh
3 Changes all spaces in file names to underscores and converts them to lowercase. This can be useful for making the file names more compatible with systems that do not support spaces in file names or for making the file names easier to read or type. correct_file_names.sh
4 Removes any trailing whitespace characters (spaces or tabs) from the end of every file in a given directory. Trailing whitespace can cause formatting issues or interfere with certain tools and processes. remove_trailing_whitespaces.sh
5 Formats and beautifies every shell script found in the current repository. This can make the scripts easier to read and maintain by adding consistent indentation and whitespace. beautify_script.sh
6 Finds functions and classes in a Python project that are not being used or called anywhere in the code. This can help identify and remove unnecessary code, which can improve the project's performance and maintainability. dead_code.sh

Git⚓︎

# Description Code
1 Resets the local repository to match the state of the remote repository, discarding any local commits and changes. This can be useful for starting over or synchronizing with the latest version on the remote repository. reset_to_origin.sh
2 Deletes the specified branch both locally and on the remote repository. This can be useful for removing branches that are no longer needed or for consolidating multiple branches into a single branch. remove_branch.sh
3 Counts the total number of lines of code in a git repository, including lines in all branches and commits. This can be useful for tracking the size and complexity of a project over time. count_lines_of_code.sh
4 Combines multiple commits into a single commit. This can be useful for simplifying a commit history or for cleaning up a series of small, incremental commits that were made in error. squash_n_last_commits.sh
5 Removes the n last commits from the repository. This can be useful for undoing mistakes or for removing sensitive information that was accidentally committed. remove_n_last_commits.sh
6 Changes the date of the last commit in the repository. This can be useful for altering the commit history for cosmetic purposes. change_commit_date.sh
7 Downloads all of the public repositories belonging to a specified user on GitHub. This can be useful for backing up repositories. download_all_github_repos.sh
8 Squashes all commits on a specified Git branch into a single commit. squash_branch.sh
9 Counts the total lines changed by a specific author in a Git repository. contributions_by_git_author.sh

Utility⚓︎

# Description Code
1 Finds the public IP address of the device running the script. ip_info.sh
2 Deletes all files in the trash bin. empty_trash.sh
3 Extracts files with a specified extension from a given directory. extract.sh
4 Determines which programs are currently using a specified port number on the local system. program_on_port.sh
5 Converts month names to numbers and vice versa in a string. For example, "January" to "1" and "1" to "January". month_to_number.sh
6 Creates command aliases for all the scripts in a specified directory, allowing them to be run by simply typing their names. alias_all_the_scripts.sh
7 Generates a random integer within a given range. The range can be specified as arguments to the script. rand_int.sh
8 Generates a random password of the specified length, using a combination of letters, numbers, and special characters. random_password.sh
9 Measures the time it takes to run a program with the specified input parameters. Output the elapsed time in seconds. time_execution.sh
10 Downloads the audio from a YouTube video or playlist in MP3 format. Specify the video or playlist URL and the destination directory for the downloaded files. youtube_to_mp3.sh
11 Clears the local caches in the user's cache directory (e.g. ~/.cache) that are older than a specified number of days. clear_cache.sh
12 Resizes all JPG files in the current directory to a specified dimension (A4). resize_to_a4

References⚓︎

Full Reference List & Details

Official Documentation⚓︎

Guides and Tutorials⚓︎

Learning Platforms⚓︎

Community and Support⚓︎

Tools and Utilities⚓︎

Books⚓︎

  • GNU Bash Manual
    The official technical reference for all shell commands.
    Go to Manual

  • The LDP
    A comprehensive collection of guides for Linux admins. PDF
    Go to TLDP

  • Greg's Wiki
    Community for learning shell scripting. Bash Programming
    Go to Guide

  • Advanced Guide
    Deep exploration of advanced shell scripting techniques.
    Go to ABS

  • Bash Hackers
    Explanations of practical usage and common pitfalls.
    Go to Archive

  • Codecademy
    Interactive command line platform for beginners.
    Go to Course

  • edX Foundation
    Professional courses covering Linux proficiency.
    Go to edX

  • Stack Exchange
    Q&A community for users of Un*x-like systems. Stack Home
    Go to Q&A

  • r/bash
    Discussion and questions about shell programming.
    Go to Reddit

  • ShellCheck
    Essential tool to find and fix bugs in your scripts.
    Go to Tool

  • ExplainShell
    Breaks down complex commands into explanations.
    Go to Tool

  • Oh My Zsh
    Community framework for managing shell configs. Github
    Go to Site

  • Learning Bash
    Comprehensive programming guide, C. Newham. Github PDF
    View Book

  • Bash Bible
    Covering everything from basics to advanced topics.
    View Book

  • Bash Cookbook
    Pract. recipes: Various scripting tasks. Github examples
    View Book


  1. Lists every unit file installed on disk with its enabled state, including units that are not currently loaded. systemctl list-units only shows units that are loaded in memory. ↩

  2. Run this after creating or editing unit files or drop-ins so systemd re-reads them. It does not restart services that are already running. ↩

  3. Equivalent to a disable followed by an enable. It recreates the unit's symlinks from its current [Install] section, which is useful after that section has changed. ↩

  4. Masking links the unit to /dev/null, so it cannot be started manually or pulled in as a dependency. This is stronger than disabling, and unmask reverses it. ↩