We have several different shell scripts that we run on a daily basis. Sometimes one of the computer operators will execute the shell script as the wrong user (Root for example). This screws up the permissions and owenership on all of the files that the script just touched!!AAAARRGGGGGGHHH!
I am looking for a way, when the script fires, to see who is running it.
The solution to this challenge is surprisingly straightforward, and it revolves around using the Unix command id to check the user’s ID, or, even more easily, using whoami (not to be confused with a Jackie Chan movie of the same name!)
When run by itself, whoami looks like this:
taylor
That should be sufficient to give you the clue on how to implement the test you seek:
then
execute the code, we’re the right user
else
echo “You must be user ‘joe’ to run this script.”
exit 0
fi
You can modify this to match the user or set of users you want to allow, or you can negate the logic to screen out bad userIDs immediately, like this:
then
echo “You cannot run this script as root.”
exit 1
fi
Hope that’s helpful!
any shell scripts to create new unix uid ?
Hey guys i just find out about your chatin exchanging answers and queations… this is awesome. i really got my answers from your questiond you guys..braavo!
to get the “real” user (even if you use “su -“), the who command can be used with either the -m flag OR in the form who ARG1 ARG2 (“who am i” or “who yo daddy”).
id or $UID will NOT give you this if you use the “-” after the su command 🙂
the “id” command can give you JUST the current user id (uid) or JUST the current group id (gid) using the -u or -g flags respectively. This is nice for shell scripts like:
——————————————–
if [ `id -u` -ne 0 ]
then
echo “You must be root to execute `basename $0`”
fi
How to you do this within a tsch shell?
Thanks for the information. Was helpful with my script which needs to be executed as root.
Thanks a bunch!!!
Cheers!
in fact UID don’t become 0 if user use “sudo” instead of become root
ggjones1, I don’t think that’d be too reliable. What if I ran a script like this:
UID=0 runmyscript.sh
and then had a simple test internally to see if UID was zero?
What about using the bash shell’s built in $UID variable?
It only prints out a number, but makes for easy checks against root (0).
how can add a new user account in the text mode or terminal
how can i check if the user exist or not.
note that I can check it in /etc/passwd
but I wanna make it in script to tell me directly if the user exist or not.
same for the group.
thank you.
if you wanted you could also use environment variables to solve both of these problems,
echo $USER – user name
echo $LOGNAME – logname
echo $PWD – print working directory
to view all environment variables type ‘printenv’ (no quotes)
Um, that’d be one of the most basic Unix commands:
pwd
just like whoami gives u the user name, i want to know a thinkg which shud tell me
whereami i.e where am i on file system
any 1 help