BASH Scripting Reference

BASH Scripting Reference

Functions

function double()
{
   Result = $1 * 2
}
Double 12

If / Elif / Else

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

/var/www/html/data/pages/bash_scripting_reference.txt · Last modified: 2024/07/25 18:55
CC Attribution-Share Alike 4.0 International Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 4.0 International