Bash Scripting


  echo Hello, World. # prints out "Hello, World."

Conditionals (Decision Control Structure)

Use conditionals to specify courses of action to be taken. In the example below, we have three possibilities to check a number in a range of other values:

#Setting a value to output
#Determine an action based on the output's value
if [ $output -eq 100 ]   #if the output is equal to 100
  echo "result is 100%"
  if [ $output -gt 100 ]   #if the output is greater than 100
    echo "result is greater than 100%"
  else     #only option is that the output is less than 100
  echo "results is less than 100%"

Read more examples about if conditionals.

Loops (Repetitive tasks)

In a loop, commands will run repeatedly until executed for all elements. Here is an example of printing numbers from 1 to 9:

#Printing numbers from 1 to 9
for i in {1..9}; do echo $i; done

If you want to have all the numbers in the same line, add the -n option:

#Numbers from 1 to 9
#Add four units in the same line
for i in {1..9}; do echo -n "$((i+4))  " ;  done

Working with files (combining conditionals with Bash commands)

Check the existence of a file to determine the size of the file as well number of words:

#Clear the terminal
tput clear

#Request the name of the file to be evaluated
printf "Enter the absolute path of the file, e.g. /home/x0y/your_file\n"
read FILE

#Evaluate the file
if [ -e $FILE ]
    printf "The $FILE has a size of $(du -h $FILE | awk '{print $1}') and it contains $(wc -w $FILE | awk '{print $1}') words.\n"
    printf "File not found..."

📝 Include 1 space between the contents of the brackets ([ and ]) and the brackets themselves.

Working with filesystems (combining conditionals with Bash commands)

Send an email if disk usage in the system has reached 90% or more:

#Run 'df -H' first to check filesystems and usage
#Then filter with `grep` to not consider Filesystem, tmpfs, nor cdrom using the options `-vE`
#Take only columns 5 and 1 with 'awk' and keep that output using `while read` to do an action
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
#Print the output with 'echo', and assign to `usep` only the first column of output, taking out '%'
  echo $output
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )
#Partition is only going to take the names of your filesystems
  partition=$(echo $output | awk '{ print $2 }' )
#if the value of `usep` is greater than or equal to 90 then you will print a message and send an email to alert
  if [ $usep -ge 90 ]; then
    echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
     mail -s "Alert: Almost out of disk space $usep%"

Learn more about Bash scripting here tutorial.