Skip to content

Step 9: Linux shell scripting

monotiller edited this page Jun 8, 2022 · 1 revision

Shell scripting crash course – beginner level

Link to discussion

  • Bash scripts ususally have the extension .sh

  • To run a bash script just use the command: ./script.sh

  • It is customary to start a script specifying what shell you want to run and where it is located:

    For example:

    #! /bin/bash

Basic bash script:

#! /bin/bash

# ECHO COMMAND
echo Hello World!

Variables

  • Uppercase by convention
  • Letters, numbers, underscores:
NAME="Florence"
echo "My name is ${NAME}"

User Input

read -p "Enter your name: " NAME
echo "Hello $NAME, nice to meet you!"

Conditionals

If statement

if [ "$NAME" == "Brad" ]
then
    echo "Your name is Brad"
fi # Opposite of 'if' for the end of an if statement

If-Else

if [ "$NAME" == "Brad" ]
then
    echo "Your name is Brad"
else
    echo "Your name is not Brad"
fi

Else-If (elif)

if [ "$NAME" == "Brad" ]
then
    echo "Your name is Brad"
elif [ "$NAME" == "Jack" ]
then
    echo "Your name is Jack"
else
    echo "Your name is not Brad or Jack"
fi

Comparison

Returns true if:

  • -eq equals
  • -ne not equals
  • gt greater than
  • ge greater than or equal to
  • lt less than
  • le less than or equal to

File conditions

Returns true if:

  • -d file the file is a directory
  • -e file the file exists
  • -f file is a file
  • -g file group id is set on a file
  • -r file file is readable
  • -s file file has a non-zero size
  • -u user id is set on a file
  • -w file is writeable
  • -x file is an executable

Case statement

read -p "Are you 18 or over Y/N " ANSWER
case "$ANSWER" in
    [yY] | [yY] [eE] [sS])
        echo "You can have a beer :)"
        ;;
    [nN] | [nN] [oO])
        echo "Sorry, no drinking
        ;
    *)
        echo "Please enter y/yes or n/no"
esac

Simple for loop

NAMES="Brad Kevin Alice Mark"
for NAME in $NAMES
    do
        echo "Hello $NAME"
done

For loop to rename files

FILES=$(ls *.txt)
NEW="new"
for FILE in $FILES
    do
        echo "Renaming $FILE to new-$FILE"
        mv $FILE $NEW-$FILE
done

While loop - read through a file line by line

LINE=1
while read -r CURRENT_LINE
    do
        echo "$LINE: $CURRENT_LINE"
        ((LINE++))
done < "./new-1.txt"

Function

function sayHello() {
    echo "Hello World"
}

sayHello

Function with params

function greet() {
    echo "Hello, I am $1 and I am $2"
}

greet "Brad" "26"

Create folder and write to a file

mkdir hello
touch "hello/world.txt"
echo "Hello World" >> "hello/world.txt"
echo "Created hello/world.txt
Clone this wiki locally