Advanced Bash-Scripting Guide

Bash Shell Scripting - Wikibooks, open books for an open world

Basic

#!/bin/bash

# comment
echo "Hello world"

Run with bash helloworld.sh

Or change permissions chmod +x helloworld.sh then run it directly ./helloworld.sh

#!/bin/bash

# create variables
user=$(whoami)
hostname=$(hostname)
directory=$(pwd)

echo "User = [$user] Host = [$hostname] Working Directory = [$directory]"

echo "Contents :"
ls

Create variables with an = sign and use those variables with $ sign. Be careful not using command name as variable name.

<aside> ⚠️ To create a variable, don’t add space around the = sign

</aside>

<aside> 📗 $<number> to get arguments, $0 is the name of the script

</aside>

Control Structures

If - Else - Elif

#!/bin/bash

variable="panda"

if [[ $variable == "panda" ]]; then
	echo "panda"
fi

if [[ $variable == "red panda" ]]; then
	echo "panda"
else
	echo "not red panda"
fi

if [[ $variable == "quiling panda" ]]; then
	echo "panda"
elif [[ $variable == "panda" ]]; then
	echo "still a panda"
else
	echo "not red panda"
fi

Numerical Comparisons