Pages

Friday, 14 July 2017

A crash course on Bash / Shell scripting concepts

if statement

if [[ $1 == "123" ]]
then echo "Argument 1 equals to 123"
else
echo "Argument 1 does not equal to 123"
fi

inverted if statement

if ! [[ $1 == "123" ]]
then echo "Argument 1 does not equal to 123"
fi

regular expression (checking for number)

regex='^[0-9]+$'
if [[ $num =~ regex ]]
then echo "This is a valid number!"
fi

while loop

NUMBER=1
while [[ $NUMBER -le "20" ]]
do echo "The number ($NUMBER) is less than 20"
NUMBER=$((NUMBER + 1))
done

awk (separate by char)

LINE=this,is,a,test
echo "$LINE" | awk -F ',' '{print The first element is $1}'

functions

MyFunction testing123
function MyFunction {
                    echo $1
                  }

read a file

while read -r LINE
do echo "Line: $LINE"

done < /tmp/inputfile.txt

case statement

case $1 in
[1-2]*) echo "Number is between 1 and 2"
        ;;
[3-4]*) echo "Number is between 3 and 4"
        ;;
5) echo "Number is 5"
        ;;
6) echo "Number is 6"
        ;;
*) echo "Something else..."
        ;;
esac

for loop

for arg in $*
do echo $arg
done

arrays

myarray=(20 "test 123" 50)
myarray+=("new element")

for element in {$myarray[@]}
do echo $element
done

getting user input

echo Please enter how your age:
read userinput
echo You have entered $userinput!

executing commands within bash

DATE1=`date +%Y%m%d`
echo Date1 is: $DATE1
DATE2=$(date +%Y%m%d) # preferred way
echo Date2 is: $DATE2

To be continued...

No comments:

Post a Comment