Friday, May 21, 2010

Checking for Root

Good programmers know to check for assumptions their code is making before executing it. For an operator, assuming that you've su'd to root before running an installer you've written is a bad idea.

The easiest way to resolve that is to simply use the EUID bash variable to check the effective user-id you're executing under and then exit if it's not zero.

I cribbed the following

if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi

From this excellent article:

http://www.cyberciti.biz/tips/shell-root-user-check-script.html

Thursday, May 20, 2010

Awk Alternative Delimiters

As it's always best to automate, it's often useful to fill the values of shell variables with the returned values of system commands.

For instance, if you wanted the ip of eth0, you could run

/sbin/ifconfig eth0

And you'd get back something like

[nsmc@nsmc-dt automation]$ /sbin/ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:26:F2:AC:C2:FE
inet addr:10.1.1.99 Bcast:10.1.3.255 Mask:255.255.252.0
inet6 addr: fe80::226:f2ff:feac:c2fe/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1142141 errors:0 dropped:0 overruns:0 frame:0
TX packets:223927 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:212209959 (202.3 MiB) TX bytes:205106885 (195.6 MiB)
Interrupt:18 Base address:0x2000

Then you could vi into your config script and export the value to a var manually.

-OR-

You could set the variable with the returned value of a system command after clearing away some noise.

Using an iterative approach, we could peel back each layer till we get the piece we want:

/sbin/ifconfig eth0 | grep "inet "

That gives us the "inet" line and not the "inet6" line.

[nsmc@nsmc-dt automation]$ /sbin/ifconfig eth0 | grep "inet "
inet addr:10.1.1.99 Bcast:10.1.3.255 Mask:255.255.252.0

But we only want the piece behind the first colon. Here we need to use a little awk trickery. awk uses spaces for it's default field delimiters. Let's change that to a colon (:) and see what we get.

[nsmc@nsmc-dt automation]$ /sbin/ifconfig eth0 \
| grep "inet " | awk -F \: '{print $2}'




10.1.1.99 Bcast

Close. Now we can pass it through a standard awk filter and just get the piece we want:

[nsmc@nsmc-dt automation]$ /sbin/ifconfig eth0 | grep "inet " \
| awk -F \: '{print $2}' | awk '{print $1}'




10.1.1.99

Now we just need to assign to our variable at runtime using the backtic's:

export PRIVATE_HOST_IP=`/sbin/ifconfig eth0 | grep "inet " \
| awk -F \: '{print $2}' | awk '{print $1}'`