Shell scripting
From Linux 101, The beginner's guide to all things Linux.
This is the fifth article on bash.
|
The Bash Articles Series |
|---|
| The shells and specifically bash | The bash environment | Processes and signals | Simple shell scripts | Shell scripting |
Text below contributed by Robert Long of (Easy-Linux.com)
This falls into the bash series, but is written in a generic manner so as to apply to shell scripting across UNIX platforms. Many UNIX systems still do not default to bash as a system shell.
Defining shell to execute in: The first line of a shell script determines the shell used to run the script, also known as the interpreter.
The syntax is typically #!<shell path>
Examples:
Use system default shell (/bin/sh):
#!/bin/sh
Use bash shell (/bin/bash):
#!/bin/bash
Use perl interpreter (/usr/bin/perl):
#!/usr/bin/perl
Other common shells to find: ksh ash csh tcsh awk
Commonalities in most shell languages:
In most shell languages you have access to certain facilities, for example: Variable creation and storage, control flow (loops, conditionals), file status, system paths and accessible executables, standard functions for formatting data, file handles (such as STDIN/STDOUT/STDERR, etc), return/exit codes.
Creating a variable:
VARIABLE = "value";
Accessing a variable:
echo $VARIABLE;
conditionals with file status:
if( -e /path/to/file ) {
do something;
}
(depending on the shell you may need to end the if statement with
fi endif
or a similar terminator
Flow control:
while true do printf "number of sendmail processes on %s\t%d\n" $HOSTNAME `ps ax | grep sendmail | wc -l`; sleep 1; done
This will show you how many sendmail processes are running, and it will update once per second.
How about running the same command across a list of systems?
for i in `seq 1 9` do ssh host$i finger username done
this is equivalent to
for i in host1 host2 .... host 9 do ssh $i finger username done
where ... is host3 host4... etc
notice we have access to system available commands and tools.
These are very useful when monitoring systems as an administrator / systems engineer.

