One of the things I do is to create - and destroy! - Linux systems on a regular basis, and invariably there are a number of stupid and annoying things that I always want to configure prior to actually starting to USE the system.
To solve this problem, I wanted to create a "system customization" script that I could drop in and run on any Ubuntu/Mint based system I create. The sticking point is that in order to work properly, it needs to run as root since it installs, slices, dices, and makes modifications to the basic system.
Since it only needs to run once after the initial install of the system, it didn't make sense to install it in /usr/bin, or run it as a cron job, as some suggested. Others suggested writing it in Perl, Python, C, or whatever. Sheesh! All I wanted to do was have the script execute a simple "Am I being run as root, or not?" test.
I searched the Web and found nothing on the subject of "How do you implement a test for "Am I root?" in a shell script.
I knew it could be done since there are only about ten-zillion scripts that make the "are you root?" test. So I fussed with it, wrote some sample scripts, made absolutely hideous mistakes, and then came up with an answer that worked.
The result of this is the following snippet of code:
Code: Select all
# I'm using bash so that line feeds work properly. If they don't, add "/n" to the end of each line.
# ---- add additional comments, or code, here ----
# Check if I am root. If not, print an explanatory error and exit
if [ $myname != "root" ]; then
Oops! This script needs to be run as root, but you are logged in as \""$myname"\"
Try running the script again with \"sudo\" like this:
sudo [this script's name]
# We're running as root, so let's go!
# ---- insert rest of script here ----
Hopefully this will help other newbie script writers handle the test for "am I root?" in a script.
What say ye?