27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

fi<br />

$UID<br />

exit 0<br />

user id number<br />

current user's user identification number, as recorded in /etc/passwd<br />

This is the current user's real id, even if she has temporarily assumed another identity through su.<br />

$UID is a readonly variable, not subject to change from the command line or within a script, and is<br />

the counterpart to the id builtin.<br />

Example 9−5. Am I root?<br />

#!/bin/bash<br />

# am−i−root.sh: Am I root or not?<br />

ROOT_UID=0 # Root has $UID 0.<br />

if [ "$UID" −eq "$ROOT_UID" ] # Will the real "root" please stand up?<br />

then<br />

echo "You are root."<br />

else<br />

echo "You are just an ordinary user (but mom loves you just the same)."<br />

fi<br />

exit 0<br />

# ============================================================= #<br />

# Code below will not execute, because the script already exited.<br />

# An alternate method of getting to the root of matters:<br />

ROOTUSER_NAME=root<br />

username=`id −nu` # Or... username=`whoami`<br />

if [ "$username" = "$ROOTUSER_NAME" ]<br />

then<br />

echo "Rooty, toot, toot. You are root."<br />

else<br />

echo "You are just a regular fella."<br />

fi<br />

See also Example 2−2.<br />

The variables $ENV, $LOGNAME, $MAIL, $TERM, $USER, and $USERNAME are not<br />

Bash builtins. These are, however, often set as environmental variables in one of the<br />

Bash startup files. $SHELL, the name of the user's login shell, may be set from<br />

/etc/passwd or in an "init" script, and it is likewise not a Bash builtin.<br />

tcsh% echo $LOGNAME<br />

bozo<br />

tcsh% echo $SHELL<br />

/bin/tcsh<br />

tcsh% echo $TERM<br />

Chapter 9. Variables Revisited 73

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!