Skip to content

Instantly share code, notes, and snippets.

@tab58
Last active April 26, 2020 19:48
Show Gist options
  • Save tab58/655bb4495840120ec0cb41ded92c2c5a to your computer and use it in GitHub Desktop.
Save tab58/655bb4495840120ec0cb41ded92c2c5a to your computer and use it in GitHub Desktop.
Bash Cheat Sheet

Bash Cheat Sheet

Common Bash Program Operations

sed: Replace string occurrences with another string.

sed 's/hello/world/' input.txt > output.txt

Language Syntax

Variables

Example Description
VAR=VALUE Setting a variable
$VAR Reading a value from a variable
  • Variables can be uppercase, lowercase, or a mixture.

Output of a command to variable:

myvar=$(ls /etc | wc -l)
echo There are $myvar entries in the directory /etc

Exporting variables for use with other scripts called within main script:

export var1
./script2.sh

Quotes

  • Single quotes treat every character literally.
  • Double quotes allow substitution of variable values.

Command Line Variables

Variable Description
$0 The name of the Bash script
$<N> The first N arguments, 0-9
$# The number of arguments that were passed to the Bash script
$@ All the arguments passed to the Bash script
$? The exit status of the most recently run process
$$ The process ID of the current script
$USER The username of the user running the script
$HOSTNAME The hostname of the machine running the script
$SECONDS The number of seconds since the script was started
$RANDOM Returns a different random number each time it's referred to
$LINENO Returns the current line number in the Bash script

User Input

Example Description
read $varname Read user input into variable varname
read -p 'Username: ' uservar Prompts for user input (-p) and saves it as uservar
read -sp 'Password: ' passvar Prompts user for silent input (-sp) and saves it as passvar
read $car1 $car2 $car3 Reads user input and splits on whitespace to supply variables (passes blank or null for fewer items, combines extra input to the last variable)
cat stdin Grabs data from the file representing STDIN

Arithmetic

Example Description
let a=5+4 Does the arithmetic operation and saves it to variable a
let "a = 5 + 4" Same as above but uses a string
let "a = $1 + 30" Adds the first command line argument to 30 and saves result to a
expr 5 + 4 Evaluates to 9 and is printed to the console (spaces required)
expr $1 + 4 Adds 4 to the first command line argument and result is printed to the console
a=$(expr 5 + 4) Evaluates the inner expression and saves result to a
a = $((4 + 5)) Evaluates the arithmetic expression and saves result to a
a = $((4+5)) Same as above
b = $(( a + 3 )) Adds 3 to the value of the variable a and saves result to b
b = $(( $a + 3 )) Same as above
(( b += 3 )) Adds 3 to the value of b and stores it in b
a=$(( 4 * 5 )) Multiplies 4 and 5, stores the result in a (no escape needed for double parens)

Valid arithmetic operators:

  • +,-,\*,/
  • ++, +=
  • --, -=
  • %

Length of a variable

a="Hello World"
echo ${#a} # 11
b=4953
echo ${#b} # 4

Comparison Statements

If Statements

if [ $1 -gt 100 ]
then
  echo "Large number."
fi

Switch Statements

case $COUNTRY in

  Lithuania)
    echo -n "Lithuanian"
    ;;

  Romania | Moldova)
    echo -n "Romanian"
    ;;

  Italy | "San Marino" | Switzerland | "Vatican City")
    echo -n "Italian"
    ;;

  *)
    echo -n "unknown"
    ;;
esac

Comparison Operators

Operator Description
! <STMT> Statement is false
-n <STRING> Length of string is greater than zero
-z <STRING> Length of string is zero
<STR1> = <STR2> STR1 is equal to STR2
<STR1> != <STR2> STR1 is not equal to STR2
<INT1> -eq <INT2> INT1 is numerically equal to INT2
<INT1> -gt <INT2> INT1 is numerically greater than INT2
<INT1> -lt <INT2> INT1 is numerically less than INT2
-d <FILE> FILE exists and is a directory
-e <FILE> FILE exists
-s <FILE> FILE exists and its size is greater than zero (i.e. not empty)
-r <FILE> FILE exists and read permission is granted
-w <FILE> FILE exists and the write permission is granted
-x <FILE> FILE exists and the execute permission is granted

Loops

Keywords Description
break Breaks out of the loop
continue Continues on to the next iteration of the loop

While Loops

counter=1
while [ counter -le 10 ]
do
  echo $counter
  ((counter++))
done

Until Loops

counter=1
until [ counter -gt 10 ]
do
  echo $counter
  ((counter++))
done

For Loops

names='Tom Dick Harry'
for name in $names
do
  echo $name
done

Select Loops

names='Tom Dick Harry'
select name in $names
do
  if [ $name == 'Quit' ]
  then
    break
  fi
  echo Hello $name
done

Ranges

Example Description
for value in {1..5} Steps through values from 1 to 5 by 1 (1,2,3,4,5)
for value in {10..0..1} Steps through values from 10 to 0 by 2 (10,8,6,4,2)

Functions

Declarations:

function_name () {
  <commands>
}
# OR
function function_name () {
  <commands>
}

Passing Arguments:

printer_fn () {
  echo Hello $1
}
printer_fn Mars # Hello Mars
printer_fn Jupiter # Hello Jupiter
  • Returning function status codes can be retrieved with $?.
  • Returning values from functions can be done through command substitution.
lines_in_file () {
  cat $1 | wc -l
}
num_lines=$( lines_in_file $1 )
echo The file $1 has $num_lines lines in it.

Variable Scope

Variables by default are global. Local variables need to be declared as such:

var_change () {
local var1='local 1'
echo Inside function: var1 is $var1 : var2 is $var2
var1='changed again'
var2='2 changed again'
}
var1='global 1'
var2='global 2'
echo Before function call: var1 is $var1 : var2 is $var2 # Before function call: var1 is global 1 : var2 is global 2
var_change # Inside function: var1 is local 1 : var2 is global 2
echo After function call: var1 is $var1 : var2 is $var2 # After function call: var1 is global 1 : var2 is 2 changed again

Overriding functions

Functions can be overridden by naming a function the same name in the script:

#!/bin/bash
# Create a wrapper around the command ls
ls () {
  command ls -lh
}
ls

Note: The keyword command is necessary to avoid an infinite loop.

User Interface

The command tput allows for customization of printing and cursor placement in the terminal. Some basic commands are:

Command Description
tput cols Returns the number of columns the terminal has.
tput lines Returns the number of lines the terminal has.
tput clear Clears the terminal.
tput cup Places the cursor at a row and column.
tput bold Turns bold text on.
tput sgr0 Clears any changes made to the terminal (such as bold).

Attributions

Info gathered from tutorials found at Ryan's Tutorials (https://ryanstutorials.net/).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment