Skip to Content
Shell Scripting: Expert Recipes for Linux, Bash, and More
book

Shell Scripting: Expert Recipes for Linux, Bash, and More

by Steve Parker
August 2011
Beginner to intermediate
600 pages
14h 29m
English
Wrox
Content preview from Shell Scripting: Expert Recipes for Linux, Bash, and More

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Command Line and Shell Scripting Techniques

Linux Command Line and Shell Scripting Techniques

Vedran Dakic, Jasmin Redzepagic
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781118166321Purchase bookDownloads