Skip to content

Instantly share code, notes, and snippets.

@keinydev
Last active January 20, 2023 21:21
Show Gist options
  • Save keinydev/cd00e2eef193325574301d78b7549844 to your computer and use it in GitHub Desktop.
Save keinydev/cd00e2eef193325574301d78b7549844 to your computer and use it in GitHub Desktop.

Programming with Bash


Bash Series

Basic Bash commands

🔵 Programming with Bash

Bash Control Structure

User interaction with Bash


Creating a Bash script

script_name.sh

#!/usr/bin/env bash
echo "Hello there"

Executable Bash script

keinydev@laptop:~$ chmod +x script_name.sh #Makes it executable
keinydev@laptop:~$ ./script_name.sh        #Executes the script

Working with variables

Setting variables

Common way to declare a variable

keinydev@laptop:~$ fruit="apple"  #Sets a value
keinydev@laptop:~$ echo $fruit    #Prints the value
keinydev@laptop:~$ fruit="orange" #Update the value
keinydev@laptop:~$ echo $fruit    #Prints the value

Declaring readonly variables

keinydev@laptop:~$ declare -r country="Colombia"  #If you try to update the value, it shows an error

Declaring variables with lowercase format

keinydev@laptop:~$ declare -l lowercase_var="FIND some VALUE" #Sets the value in lowercase

Declaring variables with uppercase format

keinydev@laptop:~$ declare -u uppercase_var="FIND some value" #Sets the value in uppercase

Declaring integers

keinydev@laptop:~$ declare -i number=5 #Sets an integer value

Show all the variables in the current sesion

keinydev@laptop:~$ declare -p

Aritmetic operations

keinydev@laptop:~$ echo $((8/4))
keinydev@laptop:~$ echo $(( (4*3) + 2 + (10/3)))

See how does it change the value using echo

keinydev@laptop:~$ number=1      #Sets a value
keinydev@laptop:~$ ((number++))  #Incrementing by 1
keinydev@laptop:~$ ((number+=8)) #Adds the variable
keinydev@laptop:~$ ((number*=2)) #Multiplication by 2
keinydev@laptop:~$ ((number/=2)) #Division by 2
keinydev@laptop:~$ ((number-=2)) #Decrementing by 2
keinydev@laptop:~$ ((number--))  #Decrementing by 1

Using integer variables

keinydev@laptop:~$ declare -i number=5 #Sets an integer value
keinydev@laptop:~$ number=$number+5    #Adds a new value to the variable

Note: To do more precise calculations, use bc or awk. Here is an example:

keinydev@laptop:~$ declare -i n1=1
keinydev@laptop:~$ declare -i n2=3
keinydev@laptop:~$ a=$(echo "scale=3; $n1/$n2" | bc) #Prints division with decimals

Comparisons (tests)

  • 0 = true
  • 1 = false

Check if directory exists

keinydev@laptop:~$ [ -d /dir_name ]; echo $?

Check if filename exists

keinydev@laptop:~$ [ -a /dir_name/file_name ]; echo $?

String comparison

keinydev@laptop:~$ [ "same" = "same" ]; echo $? #True
keinydev@laptop:~$ [ "same" = "diff" ]; echo $? #False

Number comparison

keinydev@laptop:~$ [ 5 -lt 6 ]; echo $?   #Less than 
keinydev@laptop:~$ [ ! 5 -lt 6 ]; echo $? #Less than negator (inverse)

Note: it is important to keep space between operators

Extended tests

keinydev@laptop:~$ [[ 5 -lt 6 && "cat" = "cat" ]]; echo $?  #Multiple statement comparisons

Show something if response match

keinydev@laptop:~$ [[ -d ~ ]] && echo ~ is a directory                #Prints message
keinydev@laptop:~$ [[ -d dir_name ]] && echo dir_name is a directory  #Prints message
keinydev@laptop:~$ true && echo "yeah"                                #Prints yeah!
keinydev@laptop:~$ false && echo "yeah"                               #Does not print anything

One example of regular expressions

keinydev@laptop:~$ [[ "cat" =~ c.* ]]; echo $?; #Check if string start with "c"

Formatting and styling text output

keinydev@laptop:~$ echo -e "Name\t\tNumber"; echo -e "John\t\t123" #Shows a table
keinydev@laptop:~$ echo -e "This text\nbreaks over\nthree lines"   #Breaking lines

Notification sound

keinydev@laptop:~$ echo -e "\a" #It sounds the notification tone if you have it enabled

Terminal color

Color FG BG Color FG BG Style
Black 30 40 Brigth Black 90 100 Reset 0
Red 31 41 Brigth Red 91 101 Brigth 1
Green 32 42 Brigth Green 92 102 Dim 2
Yellow 33 43 Brigth Yellow 93 103 Italic 3
Blue 34 44 Brigth Blue 94 104 Underlined 4
Magenta 35 45 Brigth Magenta 95 105 Blinking 5
Cyan 36 46 Brigth Cyan 96 106 Inverted 7
White 37 47 Brigth White 97 107 Strikethrough 9
keinydev@laptop:~$ echo -e "\033[33;44mColor Text\033[0m" #See that "33;44" correspond to FG and BG color

script_name.sh

#!/usr/bin/env bash
style="\033[9;31;40m"  #Try changing 9 value for a different style
red="\033[31;40m"      #Try changing 31:40 for another FG and BG
none="\033[0m"         #Resets the style

echo -e $style"ERROR:"$none$red" Something went wrong"$none

Arrays

Create an array

keinydev@laptop:~$ declare -a fruits=("orange" "banana" "apple") #Sets an array

Get a value from the array

keinydev@laptop:~$ echo ${fruits[1]} #Prints banana 

Add a value in specific position

keinydev@laptop:~$ fruits[5]="grapes"

Add a value in the last position of the array

keinydev@laptop:~$ fruits+=("mango")

List all values

keinydev@laptop:~$ echo ${fruits[@]} #Prints all values

Create an associative array

keinydev@laptop:~$ declare -A employees          #Declare array
keinydev@laptop:~$ employees[name]="Keiny"       #Sets a value
keinydev@laptop:~$ employees["last name"]="Doe"  #Sets a value
keinydev@laptop:~$ echo Hello ${employees[name]} ${employees["last name"]}

Little system report

script_name.sh

#!/usr/bin/env bash
free_space=$(df -h / | awk 'NR==2 {print $4}')
free_memory=$(free -h | awk 'NR==2 {print $4}')

green_text="\033[32m"
bold="\033[1m"
normal="\033[0m"

printf -v log_date "%(%Y-%m-%d)T"

echo -e "$bold Quick system report for $green_text $HOSTNAME$normal"
printf "\tKernel Release:\t%s\n" "$(uname -r)"
printf "\tBash Version:\t%s\n" "$BASH_VERSION"
printf "\tFree Storage:\t%s\n" "$free_space"
printf "\tFree Memory:\t%s\n" "$free_memory"
printf "\tFiles in pwd:\t%s\n" "$(ls | wc -l)"
printf "\tGenerated on:\t%s\n" "$log_date"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment