O'Reilly logo

Shell Scripting: Expert Recipes for Linux, Bash, and More by Steve Parker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

identity, groups, and getent

One common use of the id command is to ensure that a script is being run with the appropriate privileges. This is not particularly useful for enforcing security mechanisms, as scripts can easily be copied and edited, but sometimes it is useful to inform the user that the script will not work as expected if they are not root. For example, this short script displays configured network adapters and their current speeds. The ethtool command requires root privileges to perform its task, so it makes sense to bail out instead of failing to work properly.

download.eps
cat nicspeed.sh
#!/bin/bash
# This script only works for the root user.
if [ 'id -u' -ne 0 ]; then
  echo "Error: This script has to be run by root."
  exit 2
fi
for nic in '/sbin/ifconfig | grep "Link encap:Ethernet" | \
    grep "^eth" | awk '{ print $1 }''
do
  echo -en $nic
  ethtool $nic | grep Speed:
done

When run as an unprivileged user, it refuses to continue.

./nicspeed.sh
Error: This script has to be run by root.

When run as root, the script works.

./nicspeed.sh
eth0     Speed: 1000Mb/s
eth1     Speed: 100Mb/s
eth4     Speed: 1000Mb/s
#

nicspeed.sh

Another command related to name services in general, but including the password database, is getent. getent retrieves keyed values from certain naming services (as listed in /etc/nsswitch.conf). Some of these databases can be output ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required