Bash Scripting and System Configuration | Codio

<<

cat << ThisIsTheEnd
Is this the real life?
Is this just fantasy?
Caught in a landslide,
No escape from reality
ThisIsTheEnd

Brace Expansion

The following command displays numbers 0-20 in intervals of 2

echo {0..20..2}
echo {earth,wind,fire}_{1..3}

Parameter Expansion

book="Where the Sidewalk Ends" 

Let’s replace all e’s with ampersands & using two forward slashes //.

echo ${book//e/&}

Arithmetic Expansion

#!/bin/bash
echo ~+
echo {0..100..5}
mkdir {png,jpg,pdf}_files{1..3}
touch {png,jpg,pdf}_files{1..3}/image_{1..5}
rm {png,jpg,pdf}_files{1..3}/image_{1..5}
rmdir {png,jpg,pdf}_files{1..3}
echo "6 times 3 is equal to: $(( 6 * 3 ))"
message="impossible work!"
echo ${message:2}

Command Substitution

echo "Today is $(date)."

[ ]

ls doc[1-5][a-e].png
ls doc[[:digit:]][[:lower:]].txt

File globbing

Write a command using a named character class to list all of the files that contain a number.

ls *[[:digit:]]*

printf

echo "The answers are: $(( 8 - 5)) and $(( 15 / 3 ))"
printf "The answers are: %d and %d\n" $(( 8 - 5)) $(( 15 / 3 ))
printf "%(%Y-%m-%d %H:%M:%S)T\n"
echo "System report for $HOSTNAME"
printf "Report Date:\t%(%Y-%m-%d)T\n"
printf "Bash Version:\t%s\n" $BASH_VERSION
printf "Kernel Release:\t%s\n" $(uname -r)
printf "Available Storage:\t%s\n" $(df -h)
printf "Available Memory:\t%s\n" $(free -h)
printf "Files in Directory:\t%s\n" $(ls | wc -l)

test

[ "green" = "green" ]; echo $?

0

[ 7 -lt 15 ]; echo $?

0

[ 7 -gt 15 ]; echo $?

1

Arrays

Implicit

instruments=("piano" "flute" "guitar" "oboe")

Explicit

declare -a instruments=("piano" "flute" "guitar" "oboe")
echo ${instruments[1]}

flute

echo ${instruments[@]}
for i in {0..6}; do echo "$i: ${instruments[$i]}"; done
#!/bin/bash

even=(2 4 6 8 10)
odd=(1 3 5 7 9)

[ ${even[2]} -gt ${odd[2]} ]; echo $?
[[ $((${even[4]} + ${odd[3]})) -gt 10 ]] && echo "This is larger than 10"

Associative Arrays

declare -A student
student[name]=Rodney
student["area of study"]="Systems Administration"
echo ${student[name]} is majoring in ${student["area of study"]}.

Rodney is majoring in Systems Administration.

if

declare -i a=3

if [[ $a -gt 4 ]]; then
        echo "$a is greater than 4."
else    
        echo "$a is not greater than 4."
fi
declare -i a=3

if (( "$a" > 4 )); then
        echo "$a is greater than 4."
else    
        echo "$a is not greater than 4."
fi

case

This statement checks the country entered by the user and responds with the commands nested within that particular criteria.

#!/bin/bash

echo -n "Enter the name of a country: "
read COUNTRY

echo -n "The official language of $COUNTRY is "

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

elif

#!/bin/bash

echo Enter major or minor:
read scaleType

if [[ $scaleType == 'major' ]]
then
  echo "Major scales sound bright and hopeful"
elif [[ $scaleType == 'minor' ]]
then
  echo "Minor scales sound sad and mysterious"
else
  echo "I'm sorry, I don't understand"
fi

echo "What is your favorite genre of music?"
read genre

case $genre in

  pop | Pop)
    echo "You might enjoy Ariana Grande"
    ;;

  classical | Classical)
    echo "You might enjoy Vivaldi"
    ;;

  "hip hop" | "Hip Hop" | hiphop | rap)
    echo "You might enjoy Drake"
    ;;

  dance | Dance)
    echo "You might enjoy UMEK"
    ;;

  country | Country)
    echo "You might enjoy Jason Aldean"
    ;;

  *)
    echo "Great Choice!"
    ;;
esac

for

for i in 1 2 3 4 5
do
    echo $i
done
for i in 1 2 3 4 5; do echo $i; done

Let’s create an array called favMusicals and write a for loop that displays each array item’s value to the terminal.

declare -a favMusicals=('Hamilton' 'The Lion King' 'Grease' 'West Side Story' 'Rent')

for musical in "${favMusicals[@]}"
do
  echo "I love the musical: $musical"
done

while

declare -i n=0
while (( n < 10 ))
do
       echo "n is equal to: $n"
       (( n++ ))
done

until

declare -i m=0
until (( m == 10 ))
do
        echo "m is equal to: $m"
        (( m++ ))
        sleep 1
done

Functions

briefing() {
  echo "Good Morning, $1!"  # $1 represents the first variable passed to the function
  echo "The weather today will be $2."  # $2 is the second variable passed to the function
}

echo "It's time to get ready for your day..."

briefing Tony sunny. # Here, we call the briefing function, passing Tony as variable 1 and sunny as variable 2
declare -A BPM

BPM=( [Lento]=40 [Largo]=45 [Adagio]=55 [Andante]=75, [Moderato]=95, [Vivace]=135, [Presto]=175 )

for KEY in "${!BPM[@]}"; do echo "Key: $KEY"; echo "Value: ${BPM[$KEY]}"; echo; done

currentTempo=0
while [ $currentTempo -le 40 ]
do
    echo "$currentTempo BPM is too slow to play"
    (( currentTempo+=5 ))
done

Arguments

#!/bin/bash
for i in $@
do
    echo $i
done
echo "There were $# arguments."

Options

#!/bin/bash
while getopts u:p: option; do
        case ${option} in
                u) user=$OPTARG;;
                p) pass=$OPTARG;;
        esac
done

echo "user:$user / pass: $pass"
#!/bin/bash
while getopts :u:p:ab option; do
        case $option in
                u) user=$OPTARG;;
                p) pass=$OPTARG;;
                a) echo "got the A flag";;
                b) echo "got the B flag";;
                ?) echo "I don't know what $OPTARG is!";;
        esac
done

echo "user:$user / pass: $pass"
while getopts u:p:s: option; do
        case ${option} in
                u) user=$OPTARG;;
                p) pass=$OPTARG;;
                s) skey=$OPTARG;;
        esac
done

echo "Username: $user"
echo "Password: $pass"
echo "Security Key: $skey"

read

#!/bin/bash

echo "What is your name?"
read name

echo "What is your password?"
read -s pass

read -p "What's your favorite animal? " animal

echo "Name: $name, Password: $pass, Fave Animal: $animal"

echo "Which animal"
select animal in "cat" "dog" "bird" "fish"

do
    echo "You selected $animal!"
    break
done
#!/bin/bash

echo "Which animal"
select animal in "cat" "dog" "quit"
do
       case $animal in 
               cat) echo "Cats like to sleep.";;
               dog) echo "Dogs like to play catch.";;
               quit) break;;
               *) echo "I'm not sure what that is.";;
        esac
done

read -i

#!/usr/bin/env bash

read -ep "What is your pet's name? " -i "Pabu" petname

echo $petname

if (($# < 3 )); then
    echo "This command takes three arguments:"
    echo "petname, pettype, and petbreed."

else

    echo "Pet Name: $1"
    echo "Pet Type: $2"
    echo "Pet Breed: $3"

fi

[[ -z ]]

#!/usr/bin/env bash

read -p "What would you like for dinner? [Chicken Noodle Soup] " dinner

while [[ -z $dinner ]]
do
    dinner="Chicken Noodle Soup"
done

echo "You will be having $dinner$ for dinner!"
#!/usr/bin/env bash

read -p "Please enter a 5-digit zip code: [nnnnn]" zipcode

until [[ $zipcode =~ [0-9]{5} ]]; do
    read -p "Still waiting on that zip code! [nnnnn] " zipcode
done

echo "Your zip code is $zipcode

tr

echo "dog dOg" | tr "[a-z]" "[A-Z]"

DOG DOG

echo "dog dOg" | tr "[:lower:]" "[:upper:]"

DOG DOG

echo "dog dOg" | tr [:space:] '\t'

awk

Print all of the lines of data

awk '{print}' students.txt

Print all of the lines in the file students.txt that match the pattern freshman using the command below.

awk '/freshman/ {print}' students.txt 

cut

Let’s use cut to print the first, third, and fifth characters from each line of the file pres_first.txt.

cut -c 1,3,5 pres_first.txt

Let’s print characters 2-6 from each line of pres_last.txt.

cut -c 2-6 pres_last.txt

tee

We can append information to one or more files with the -a option.

echo "that only few can see" | tee -a message1.txt message2.txt

xargs

echo 'red blue yellow' | xargs mkdir

RANDOM

echo $(( 1 + $RANDOM % 5 ))

Scripting

My solution

#!/bin/bash

###############
## VARIABLES ##
###############

declare -a tops=('top1' 'top2' 'top3' 'top4' 'top5')
declare -a bottoms=('bottom1' 'bottom2' 'bottom3' 'bottom4' 'bottom5')
declare -a shoes=('shoe1' 'shoe2' 'shoe3' 'shoe4' 'shoe5')
declare -a accessories=('accessory1' 'accessory2' 'accessory3' 'accessory4' 'accesory5')
declare -a days=('Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday')

#########################
## FUNCTION DEFINITION ##
#########################

selectWardrobe() {
  echo "Now selecting weekly wardrobe"
  for day in "${days[@]}"
  do
    index1=$(( $RANDOM % 5 ))
    index2=$(( $RANDOM % 5 ))
    index3=$(( $RANDOM % 5 ))
    index4=$(( $RANDOM % 5 ))
    index5=$(( $RANDOM % 5 ))
    top=${tops[$index1]}
    bottom=${bottoms[$index2]}
    shoe=${shoes[$index3]}
    accessory1=${accessories[$index4]}
    accessory2=${accessories[$index5]}
    echo "On $day, you should wear: $top, $bottom, and $shoe"
    echo "Pair with: $accessory1 and $accessory2"
    echo
done
}

outfitSelection() {
  echo "Generating outfit selection for $1 weeks"
  workWeek="0"
  while [ $workWeek -lt $1 ]
  do
    workWeek=$[$workWeek+1]
    echo "Week $workWeek Wardrobe:"
    selectWardrobe
  done
  echo "Enjoy $1 weeks of outfit selections"
}

#######################
## CALLING FUNCTIONS ##
#######################

outfitSelection 4 > monthlyOutfit.txt

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

Codio’s solution

#!/bin/bash

echo "Reading Loud and Clear"

##VARIABLES
declare -a tops=('Tshirt' 'V-Neck' 'Sweater' 'cardigan' 'blouse')
declare -a bottoms=('Blue Jeans' 'Black Jeans' 'Black Slacks' 'Skirt' 'Khakis')
declare -a shoes=('Sneakers' 'Flats' 'Heels' 'Oxfords' 'Whatever Feels Good')
declare -a accessories=('Watch' 'Bracelet' 'Necklace' 'Earrings' 'Hat')
declare -a days=("Monday" "Tuesday" "Wednesday" "Thursday" "Friday")

##FUNCTION DEFINITION
selectWardrobe(){
  echo "Now selecting weekly wardrobe"
  for day in ${days[@]}
  
  do
    randomTop=$(( 0 + $RANDOM % 5))
    randomBottom=$(( 0 + $RANDOM % 5))
    randomShoes=$(( 0 + $RANDOM % 5))
    randomAcc1=$(( 0 + $RANDOM % 5))
    randomAcc2=$(( 0 + $RANDOM % 5))

    echo "On $day you should wear: ${tops[randomTop]}, ${bottoms[randomBottom]}, and ${shoes[randomShoes]}"
    echo "Pair with: ${accessories[randomAcc1]} and ${accessories[randomAcc2]}"
    echo
  done
}

outfitSelection(){
  echo "Generating outfit selection for $1 weeks"

  workWeek=1
  while (( workWeek < $(( $1+1 )) ))
  do
       echo "Week $workWeek Wardrobe:"
       selectWardrobe
       (( workWeek++ ))
  done
  echo Enjoy $1 weeks of outfit selections!
  
}

##CALLING FUNCTIONS
outfitSelection 4 > monthlyOutfit.txt

while read textline
do
    echo $textline
done < /home/codio/workspace/monthlyOutfit.txt