Allison is coding...

Notes|Bash Scripting

Notes for TryHackMe | Bash Scripting.

The Basic concepts

Add # on the top line of file to comment the bash script.

Make the file.sh executable to run the script:

chmod +x bashfile.sh

Run the file with ./:

./ file.sh

echo is used to output text to the screen (like print in python).

Variables

Example code:

name="Alex"
echo $name

Use bash -x /file.sh to step through the script.

Use set -x and set +x to debug at a certain section of the code:

echo "hi"

set -x
whoami
set +x

Parameters

$0 is the filename of the bash script.

name=$1
echo $name

Sign the first argument to name.

Use read to assign the input to a variable.

echo Enter your name
read name
echo 'Hello, $name'

Arrays

cars=('audi' 'tesla' 'toyota' 'honda')

An array is separated by space (not , !).

Remove the element: unset cars[index].

Print the certain index: echo "${cars[index]}"

Conditionals

Syntax:

if [condition]
then
    something
else
    something different
fi

An example:

count=10

if [ $count -eq 10 ]
then 
    echo "true"
else 
    echo "false"
fi

Some operators:

OperatorDescription
-eq“equal”. Checks if the value of two operands are equal or not; if yes, then the condition becomes true.
-ne“negative”. Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true.
-gt“>”. Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true.
-lt“<”. Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true.
-ge“≥”. Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true.

Further to explore: