Understanding Bash Shell Scripts

A shell script can simply contain commands that are sequentially executed

Scripts normally work with variables to make them react differently in different environments

Conditional statements such as for, if, case, and while can be used

A shell will always be available to interpret code from shell scripts

Bash shell scripts are not idempotent, meaning that the same script will yield the same result every time it is ran

Essential Shell Script Components

A shell script needs to be executable:

chmod +x script.sh

The system refers to the $PATH variable to locate commands:

echo $PATH

Due to this being the case, include ./ to the beginning of the script’s name to run it

Anatomy of a Bash Shell Script

#!/bin/bash
# shell script comment

echo which directory should be activated?

read DIR

cd $DIR
pwd
ls

#!/bin/bash: States the interpreter to be used to run this script

echo which directory should be activated?: Will print the provided message

read DIR: Asks for user input and stores the input in the variable DIR

Using Loops in Shell Scripts

Bash Conditional Statements

if...then...fi: If Else statement

while...do...done: While loop

until...do...done: Used to execute a given set of commands as long as the given condition is false

case..in...esac: Used to simplify complex conditionals that require multiple different choices

for...in..do..done: Used for range of arguments

if Statement

#!/bin/bash

if [ -z $1 ]
then
	echo provide an argument
	exit 6
fi

echo the argument is $1

[-z $1]: Test command, which more information can be found in man test

-z: Tests if the length of a string is equal to zero

$1: The argument provided when running the script

then: Runs the following lines if the condition statement is true

exit 6: Exits the script with the exit code of 6

fi: Ends the if statement

while Loop

#!/bin/bash

COUNTER=$1
COUNTER=$(( COUNTER * 60 ))

minusone(){
	COUNTER=$(( COUNTER - 1))
	sleep 1
}

while [ $COUNTER -gt 0 ]
do
	echo $COUNTER seconds left
	minusone
done

[ $COUNTER = 0 ] && echo time is up && minusone
[ $COUNTER = "-1" ] && echo one second late && minusone

while true
do
	echo now ${COUNTER#-} seconds late
	minusone
done

COUNTER=$(( COUNTER * 60 )): Calculation that multiplies COUNTER by 60

minusone(){: Initializes a function

sleep 1: Sleeps for one second

while [ $COUNTER -gt 0 ]: Initializes while loop with a test

done: Ends the while loop

[ [ $COUNTER = 0] && and [ $COUNTER= "-1" ] &&: Test with a logical operator, which is essentially an if statement

while true: Initializes an infinite loop

${COUNTER#-}: Pattern matching operator

Leave a Reply

Your email address will not be published.