Bash CheatSheet

Reference Lynda.com - Up and running Bash Scripting

Bash script syntax

To run like bash script.

  1. #!/bin/bash

Comments

  1. # comment

Use extension .sh for shell and bash files.

To run a bash file use:
bash myscript.sh

To make the script executable without the bash command use:

  1. chmod +x myscript.sh
  2. ./myscript.sh

top

Echo

To print empty line.

  1. echo

To print all as strings. Escape special characters with a \.

  1. greeting="hello"
  2. # No quotes
  3. echo $greeting, world \(planet\)! # hello, world (planet)!
  4. # Single quotes
  5. echo '$greeting, world (planet)!' # $greeting, world (planet)!
  6. # Double quotes
  7. echo "$greeting, world (planet)!" # $hello, world (planet)!
  8. # Double quotes escaped variables
  9. echo "\$greeting, world (planet)!" # $greeting, world (planet)!

top

Variables

Must not have whitespaces next to the equal sign.

Call them with a $.

  1. a=Hello
  2. b="Good Morning"
  3. c=16
  4. echo $a
  5. echo $b
  6. echo $c
  7. echo "$b! I have $c apples."

top

Special attributes

Declare vars with special attributes

  1. declare -i d=123 # d is an integer
  2. declare -r e=456 # e is read-only
  3. declare -l f="LOLCats" # f is lolcats
  4. declare -u g="LOLCats" # g is LOLCATS

top

Special Variables

  1. echo $PWD # Returns current directory
  2. echo $HOME # Returns home directory
  3. echo $MACHTYPE # Returns machine type eg. Mac x86_64-apple-darwin12
  4. echo $HOSTNAME # Host name
  5. echo $BASH_VERSION
  6. echo $SECONDS # seconds of the session open

Run commands inside variables.

  1. a=$(pwd)
  2. echo $a # current directory

top

Arithmetic

To do arithmetic operations we need to wrap into (( )).

:boom: Only integers are supported.

Operation Operator
Exponentiation $a ** $b
Multiplication $a * $b
Division $a / $b
Modulo $a % $b
Addition $a + $b
Subtraction $a - $b
  1. echo $((2+3)) # 5
  2. d=2
  3. e=$((d+2)) # 4
  4. ((e++)) # 5
  5. ((e+=4))

top

Comparison operations

[[ expression ]] to run comparison expressions

Result is

  • 0: TRUE
  • 1: FALSE

Non-numeric comparison

The following work for non-numeric values:

Operation Operator
Less than [[ $a < $b ]]
Greater than [[ $a > $b ]]
Less than or equal to [[ $a <= $b ]]
Greater than or equal to [[ $a >= $b ]]
Equal [[ $a == $b ]]
Not equal [[ $a != $b ]]

Compare strings

  1. #!/bin/bash
  2. # this is a bash script
  3. echo working with Comparison operators
  4. [[ "cat" == "cat" ]]
  5. echo $?
  6. # 0

top

Integer comparison

For working with Integers use the following:

Operation Operator
Less than [[ $a -lt $b ]]
Greater than [[ $a -gt $b ]]
Less than or equal to [[ $a -le $b ]]
Greater than or equal to [[ $a -ge $b ]]
Equal [[ $a -eq $b ]]
Not equal [[ $a -ne $b ]]

Compare integers

  1. [[ 10 -gt 2 ]]
  2. echo $?
  3. # 0

top

Logic Operators

Operation Operator
Logical AND [[ $a && $b ]]
Logical OR [[ $a || $b ]]
Logical NOT [[ ! $a ]]

top

String Null Value

Operation Operator
String is null [[ -z $a ]].
String is not null [[ -n $a ]].

Check if string is null

  1. echo is string null?
  2. a=""
  3. b="cat"
  4. [[ -z $a ]]
  5. echo $?
  6. [[ -z $b ]]
  7. echo $?

top

File operators

Operator Operation Example
-L is symlink [[ -L $file ]]
-h is symlink [[ -h $file ]]
-d is directory [[ -d $file ]]
-e is archive [[ - $file ]]
-f is file [[ - $file ]]
-r is readable file [[ -r $file ]]
-w is writeable file [[ -w $file ]]
-x is executable file [[ -x $file ]]
-s is file size > 0 [[ -s $file ]]

More operators

top

Working with Strings

Concat strings

  1. #!/bin/bash
  2. # this is a bash script
  3. echo Working with Strings
  4. echo
  5. echo Concat strings
  6. a="hello"
  7. b="world"
  8. c=$a$b
  9. echo $c # helloworld

top

Length of strings

  1. echo 'Length of strings use #'
  2. echo ${#a} # 5
  3. echo

top

Substring

  1. echo Get the substring
  2. d=${c:3} # specify the starting point for the substring
  3. echo $d # loworld

top

With certain length

  1. echo Get substring with certain length
  2. e=${c:3:4} # in this case 4 is the length of the substring
  3. echo $e # lowo

top

Starting from the end

  1. echo Get substring starting from the end of the string
  2. f=${c: -4} # get the last 4 chars of the string
  3. echo $f # orld
  4. echo Now get the first 3 letters of the last 4 letters
  5. g=${c: -4:3}
  6. echo $g # orl
  7. echo

top

Replace string

  1. echo Replace string
  2. fruits="apple banana kiwi cherry"
  3. echo ${fruits/banana/melon} # replace banana with melon

top

Coloring and Styling text

Styled text tput

tput is a command that allows styling and coloring text

Styles

Style Command
Foreground tput setaf [0-7]
Background tput setab [0-7]
No Style tput sgr0
Bold tput bold
Low Intensity tput dim
Underline tput smul
Blinking tput blink
Reverse tput rev

top

Colors

Color setaf setab
Black 0 0
Red 1 1
Green 2 2
Yellow 3 3
Blue 4 4
Magenta 5 5
Cyan 6 6
White 7 7

top

Example script

  1. #!/bin/bash
  2. # this is a bash script
  3. echo 'Colors & Styles'
  4. echo
  5. flashred=$(tput setab 7; tput setaf 1; tput blink)
  6. red=$(tput setaf 1)
  7. none=$(tput sgr0)
  8. echo $flashred"ERROR:"$none$red" Something went wrong."$none

:boom: To see a list of tput commands type man terminfo

top

Date

Date is not part of bash but it ships with Unix

  1. #!/bin/bash
  2. # this is a bash script
  3. echo 'DATE'
  4. echo
  5. echo 'Use the operator + to specify the date format'
  6. date +"%d-%m-%Y" # 30-may-1980 (day month year)
  7. date +"%H-%M-%S" # 20-40-24 (hour minutes seconds)

top

Printf

It is like echo but with more features
Printf comes with Unix, not bash, so you can save it with -v to a variable and print it with echo.

  1. #!/bin/bash
  2. # this is a bash script
  3. echo 'Printf'
  4. echo
  5. printf "Name:\t%s\nID:\t%04d\n" "Jorge" "27"
  6. # Name: Jorge
  7. # ID: 0027
  8. echo
  9. echo
  10. # %s and %04d indicate where to print the values Jorge and 27
  11. today=$(date +"%d-%m-%Y")
  12. time=$(date +"%H:%M:%S")
  13. printf -v d "Current User:\t%s\nDate:\t\t%s @ %s\n" $USER $today $time
  14. echo "$d"
  15. # Current User: user
  16. # Date: 20-03-2015 @ 10:23:42

top

Arrays

Arrays don’t need commas.
They are initialized with () and called with [].

These arrays behave like JavaScript where the size is flexible.

  1. #!/bin/bash
  2. # This is a bash script
  3. echo 'Arrays'
  4. echo
  5. a=()
  6. b=("apples" "bananas" "lemons")
  7. echo ${b[2]} # lemons
  8. b[5]="kiwi"
  9. echo ${b[@]} # apples bananas lemons kiwi
  10. b+=("oranges") # add at the end of the array
  11. echo ${b[@] : -1} # show the last element in the array

top

Associative Arrays

This type of arrays is more like the object literals in JavaScript where the keys are strings instead of numbers.

  1. #!/bin/bash
  2. # This is a bash script
  3. echo 'Associative Arrays'
  4. echo
  5. # NOTE: This just works for Bash version > 4.0
  6. declare -A peopleAges
  7. peopleAges[John]=50
  8. peopleAges["John Wayne"]=79
  9. echo ${peopleAges["John Wayne"]}

top

Reading and writing text files

  1. #!/bin/bash
  2. # This is a bash script
  3. echo 'Text Files'
  4. echo
  5. echo "Some Text" > file.txt # creates or overwrites file.txt with the string "Some Text"
  6. echo "Add this text" >> file.txt # Appends the string to the end of file.txt
  7. > file.txt # empties file.txt
  8. echo "Add this text" >> file.txt # Appends the string to the end of file.txt
  9. echo "text2" >> file.txt
  10. echo "text3" >> file.txt
  11. # this loop reads each line in file.txt
  12. while read f; do
  13. echo $f
  14. done < file.txt

top

Using a text file as an input for a command

ftp.txt

  1. open mirrors.xmission.com
  2. user anonymous nothinghere
  3. ascii
  4. cd gutenberg
  5. get GUTINDEX.00

Using the file.txt as input

  1. #!/bin/bash
  2. # This is a bash script
  3. echo 'Text File as input for a command'
  4. echo
  5. echo 'You can use cat to read a file'
  6. cat < file.txt
  7. echo
  8. echo 'You can use any command and use input from a file.'
  9. ftp -n < ftp.txt
  10. ls # you should see the GUTINDEX.00 file in your current directory

top

Here document

You can specify the start and end of an text as input to a command with a keyword.
In the following script you can see that it uses a text blob for cat and then another one for ftp.

  1. #!/bin/bash
  2. # This is a bash script
  3. echo 'Here documents'
  4. echo
  5. echo 'Using here document to know until when to print cat.'
  6. cat << EndOfText
  7. This is a
  8. multiline
  9. text string
  10. EndOfText
  11. # cat will use input until it sees EndOfText #
  12. echo
  13. echo 'Using tabs with the dash flag'
  14. ftp -n <<- DoneWithTheUpdate
  15. open mirrors.xmission.com
  16. user anonymous nothinghere
  17. ascii
  18. cd gutenberg
  19. get GUTINDEX.01
  20. bye
  21. DoneWithTheUpdate
  22. # this marks the end of the input for the command ftp #

top

The if statement

  1. #!/bin/bash
  2. # The if statement
  3. echo 'if statement'
  4. a=2000
  5. if [ $a -gt 1000 ]
  6. then
  7. echo $a is greater than 1000!
  8. else
  9. echo $a is not greater than 1000
  10. fi

top

The if statement using regular expressions.

  1. echo 'if statement using regular expressions'
  2. s="This is 1 string!"
  3. if [[ $s =~ [0-9]+ ]]; then # Note the double square brackets are used because Regex also uses them.
  4. echo "There are some numbers in the string: $s"
  5. else
  6. echo "There are no numbers in the string: $s"
  7. fi

top

The while loop

  1. #!/bin/bash
  2. # The while loop
  3. i=0
  4. while [ $i -le 9 ] ; do
  5. echo i:$i
  6. ((i+=1))
  7. done
  8. # result
  9. # i:0
  10. # i:1
  11. # i:2
  12. # i:3
  13. # i:4
  14. # i:5
  15. # i:6
  16. # i:7
  17. # i:8
  18. # i:9

top

The until loop

The oposite of the while loop.

  1. # the Until loop
  2. j=0
  3. until [ $j -ge 10 ]; do
  4. echo j:$j
  5. ((j+=1))
  6. done
  7. # result
  8. # j:0
  9. # j:1
  10. # j:2
  11. # j:3
  12. # j:4
  13. # j:5
  14. # j:6
  15. # j:7
  16. # j:8
  17. # j:9

top

The for loop

  1. for i in 1 2 3
  2. do
  3. echo $i
  4. done

top

With brace expansion

  1. for j in {1..20}
  2. do
  3. echo $j
  4. done

top

Like in C languages

  1. for (( i=1; i<=10; i++))
  2. do
  3. echo $i
  4. done

top

Looping through an array

  1. arr=("apple" "banana" "lemon")
  2. for i in ${arr[@]}
  3. do
  4. echo $i
  5. done

top

Use the output of a command

  1. for i in $(ls)
  2. do
  3. echo $i
  4. done

top

Switch case

  1. #!/bin/bash
  2. a="dog"
  3. case $a in
  4. cat) echo "Feline";;
  5. dog|puppy) echo "Canine";; # dog or puppy
  6. *) echo "No match!";; # default case
  7. esac

top

Functions

  1. #!/bin/bash
  2. # Function
  3. function greet {
  4. echo "Hello $1 good $2"
  5. }
  6. echo "And now meeting"
  7. greet Jorge morning
  8. You can exit the function with `return` or exit the script with `exit 0`

top

With unspecified parameters

  1. function listallthings {
  2. i=0
  3. for f in $@; do
  4. echo $i: $f
  5. ((i+=1))
  6. done
  7. }
  8. listallthings $(ls)

top

Arguments

Operator meaning
$1 First argument
$@ Array of all arguments
$# Count of arguments
  1. for i in $@; do
  2. echo $i
  3. done
  4. echo "there are $# arguments"

top

Flags

The colon after the flag means that the flag is required.
The first colon means that any unknown flag will be passed too.
In the following case it says that the flags u and p are required. The a and b are optional.

  1. #!/bin/bash
  2. # Flags
  3. while getopts :u:p:ab option; do
  4. case $option in
  5. u) user=$OPTARG;;
  6. p) pass=$OPTARG;;
  7. a) echo "Got the A flag";;
  8. b) echo "Got the B flag";;
  9. ?) echo "Unknown flag";;
  10. esac
  11. done
  12. echo "User $user password $pass"

top

Input during execution

More flads for read command

  1. #!/bin/bash
  2. echo "What is your name?"
  3. read name
  4. echo "What is your password?"
  5. read -s pass # -s is secret mode so it won't display the input
  6. read -p "What is your favorite animal? " animal # -p allows to use inline input
  7. echo name: $name pass: $pass animal: $animal

top

Input with Select

Similar to HTML Select/option. It only accepts numbers as input.

  1. #!/bin/bash
  2. # Select
  3. select option in "cat" "dog" "quit"
  4. do
  5. case $option in
  6. cat) echo "Cats like to sleep";;
  7. dog) echo "Dogs like to play";;
  8. quit) break;;
  9. *) echo "Unknown command";;
  10. esac
  11. done

top

Ensuring a response

Patterns to ensure a response from the user

Requiring a minimum of arguments

  1. if [ $# -lt 3 ] ; then
  2. cat <<- EOM
  3. This command requires three arguments:
  4. username, userid and favorite number.
  5. EOM
  6. else
  7. # the program goes here
  8. echo "Username: $1"
  9. echo "UserID: $2"
  10. echo "Favorite Number: $3"
  11. fi

top

Requiring an input

  1. #!/bin/bash
  2. # Ensuring - pattern 2
  3. read -p "Favorite animal? " a
  4. while [[ -z $a ]] ; do
  5. read -p "I need an answer! " a
  6. done
  7. echo "$a was selected"

top

Validating input with regular expressions

  1. #!/bin/bash
  2. # Ensuring - pattern 3
  3. read -p "What year? [nnnn] " a
  4. while [[ ! $a =~ [0-9]{4} ]]; do
  5. read -p "A year, please! [nnnn] " a
  6. done
  7. echo "Selected year: $a"

top

Import files

In this case we are importing config/colors.sh

  1. source config/colors.sh

Find directories

  1. find / -type d -name 'httpdocs

The first parameter / is where to look

-name could be -iname to ignore case

also -type is not mandatory

top

Return to blog