---

Linux Gazette: Introduction to Shell Scripting

“At this point in the series, we’re getting pretty close to
what I consider the upper limit of basic shell scripting; there are
still a few areas I’d like to cover, but most of the issues
involved are getting rather, umm, involved. A good example is the
`tput’ command that I’ll be covering this month:
in order to
really understand what’s going on, as opposed to just using it,
you’d need to learn all about “termcap/terminfo” controversy
(A.K.A. one of the main arguments in the “Why UNIX Sucks” debate) –
a deep, involved, ugly issue (for a fairly decent and simple
explanation, see Hans de Goede’s fixkeys.tgz, which contains a neat
little “HOWTO”. For a more in-depth study, the
Keyboard-and-Console-HOWTO is an awesome reference on the subject).
I’ll try to make sense despite the confusion, but be warned…”

“The concept of functions is not a difficult one, but is
certainly very useful: they are simply blocks of code that you can
execute under a single label. Unlike a script, they do not spawn a
new subshell but execute within the current one. They can be used
within a script, or stand-alone. … Functions may also be loaded
into the environment, and invoked just like shell scripts; we’ll
talk about sourcing functions later on. For those of you who use
Midnight Commander, check out the “mc ()” function described in
their man page – it’s a very useful one, and is loaded from
“.bashrc”.”

“Important item: functions are created as “function
pour_the_beer () { … }” or “pour_the_beer () { … }” (the
keyword is optional); they are invoked as “pour_the_beer” (no
parentheses). Also, be very careful (as in, _do not_ unless you
really mean it) about using an “exit” statement in a function:
since you’re running the code in the current shell, this will cause
you to exit your current (i.e. the “login”) shell! Exiting a shell
script this way can produce some very ugly results, like a `hung’
shell that has to be killed from another VT (yep, I’ve
experimented). The statement that will terminate a function without
killing the shell is “return”.”

Complete
Story

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends, & analysis