====== BASH Scripting Reference ======
==== Links/Resources ====
[[https://linuxhint.com/3hr_bash_tutorial/|3 Hour Bash Tutorial]] \\
----
==== Functions ====
function double()
{
Result = $1 * 2
}
Double 12
----
==== If / Elif / Else ====
[[https://linuxhint.com/bash_if_else_examples/|link]]
if CONDITION-TO-TEST; then
CODE-TO-EXECUTE-1
elif NEXT-CONDITION-TO-TEST; then
CODE-TO-EXECUTE-2
elif NEXT-CONDITION-TO-TEST; then
CODE-TO-EXECUTE-2
else
CODE-TO-EXECUTE-2
fi
----
==== Ask a yes/no question (case insensitive comparison)====
read -p "Do it? [y/n] " yesno
if [[ "${yesno,,}" != "y" ]]; then
echo "OK. Exiting..."
exit 1 # Exit with an error code to indicate user cancelled
else
# Rest of your script if user confirms (y/Y)
echo "OK. Continuing..."
fi
----
==== Check if running as root/sudo ====
if [[ $(/usr/bin/id -u) -ne 0 ]]; then
echo "Not running as root"
exit
fi
touch /etc/test.file
if [ $? -ne 0 ]; then
echo "This command needs to be run with sudo!"
exit 1
fi
----
==== Pass Command Line Parameters ====
#!/bin/bash
echo "1st parameter = $1 "
echo "2nd Parameter = $2 "
----
==== Test if variable is empty ====
if [ -z "$var" ]
then
echo "\$var is empty"
else
echo "\$var is NOT empty"
fi
----
==== Add a user, specifying group membership ====
sudo useradd -m -g users -G sudo,docker username
sudo id username
----