Linux - Only allow root to run script

By xngo on June 17, 2019

The following will check who is running the script. If it is not root, then it will exit.

# Get username that is running this script.
WHOAMI=$(/usr/bin/whoami)
echo "$WHOAMI is running this script!"
 
if [ $WHOAMI != "root" ]; then
    echo
    echo "You must be root to run this!"
    echo
    exit 1
fi

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.