Tips from RHCEs

Featured Article: Bash Scripting on the Command Line

by Brad Smith

A lot of important processes on your Red Hat Linux system, most notably the init scripts, are written in the Bash shell's scripting language. Many do not realize, though, that this powerful administrative tool can be used from the command line as well as in script files. For example, the following shell script can be used to list all files that exist in one directory (/foo) but not in another (/bar).

#!/bin/sh

# Go through each file in /foo and... 
for filepath in /foo/*
do
# Strip off the "/foo" part, leaving only the file name 
filename=$(basename $filepath)

# if /bar/filename doesn't exist, print a message
[ ! -e /bar/$filename ] && echo "$filename is not in /bar"
done

If you only needed to do this once, this whole script could be represented as a single command line:

[user@system ]# for filepath in /foo/* ; do filename=$(basename
$filepath) ; [ ! -e /bar/$filename ] && echo "$filename is not in /bar"
; done

The only difference between this and the script above (besides the omission of comments) is that semicolons are used to separate commands instead of newlines. In fact, even these are optional. Try typing just the first line of this script:

for filepath in /foo/*

and hitting enter. Bash will recognize that the 'for' keyword marks the beginning of a longer statement and just move you to a new line instead of trying to execute anything. Bash will not attempt to actually run your for loop until it encounters the 'done' keyword.

With some practice the bash scripting language can become a very powerful tool for administrators who hate tedium. Being able to use for loops, while loops and if statements as a part of ordinary command lines makes it that much more powerful. It is also worth noting that other interpretive languages have similar features. If you are familiar with perl or python, experiment with "perl -e" and/or "python -c" for writing short perl and python scripts on the command line (or even incorporating the power of those languages into your bash scripts).