Monday, September 22, 2008

SPR720 - BASH Scripting Lab

BASH (Bourne Again SHell) is a command processor for POSIX operating systems such as Linux. Not only does it provide a command line interface, it provides scripting support by letting me place commands into a text file for later execution. BASH and its scripts give access to redirection, pipes, regular expressions and the panoply of Linux command line utilities. This is indeed a very powerful set of tools. As the possibilities of the command line open up to me I'm finding very little I can't find out about or get done inside the shell. But when I try to write scripts I find the language to be non-intuitive and just plain difficult. While there are many things that make BASH difficult for me, two stand out:
  • It's variables are untyped or (for practical purposes) just one type - string. In order to use numeric values stored as strings, there are some cryptic work-arounds.
  • 0=TRUE. In every other programming language I've used, it's the opposite. It reminds me of a scene from a movie called "The Gods Must Be Crazy" where in an African tribe, people nodded their heads to indicate "no" and shook their heads to mean "yes". At least once a script I get tripped up by this. I know it's because the Linux exit status for "job well done" is 0, but it's still a drag.
Sometimes the difficulty is compounded when both of these "gotchas" come together in forming conditionals or when evaluating strings and numbers inside the same complex expression. It's enough to make me chew the inside of my cheek. But thankfully the Internet came to my rescue, again. I found some great resources that made the process of scripting bearable, if not enjoyable. I hate to admit it, but without these resources I would not have finished my lab. So my thanks to their creators and contributors.

Here's a sample script I did for the lab:

#!/bin/bash
#
# lsname.bash # This script prints out the longest and shortest names in /etc/passwd
#


SNAME="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

LNAME=""

while IFS=: read USER PASS USERID GID GECOS HOME SHELL
do
if test ${#USER} -gt ${#LNAME}
then

LNAME=$USER
fi

if test ${#USER} -lt ${#SNAME}
then
SNAME=$USER
fi
done < /etc/passwd


echo "Longest name in /etc/passwd is $LNAME - ${#LNAME} characters"
echo "Shortest name in /etc/passwd is $SNAME - ${#SNAME} character"


---
Bash Resources
http://tldp.org/LDP/abs/html/index.html
http://wooledge.org:8000/BashFAQ
http://www.tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html

Btw, this post is not meant to be flame bait. I just needed to vent a little.

No comments: