Official website for Linux User & Developer

Shell scripting for system administrators: the basics

by Swayam Prakasha

For system administrators shell scripting can be a very useful way to drastically improve workflow. Join Swayam Prakasha to find out how you can employ some fundemental tips and techniques to make your life easier…

Before we start writing the shell scripts, we need to make sure that we have the ‘sh’ executable. In the following screenshot, we have executed the command ‘which sh’ and this command displays the location where one can find the sh executable.

Shell scripting for system administrators: the basics

The first line of any shell script is something like this:
[sourcecode language=”bash”]#!/path/to/shell
In shell scripting, anything following ‘#’ is interpreted as a comment and it will not be executed. But if it occurs in the first line with a ‘!’ following, then it is treated differently. The filename following ‘!’ is considered to point to the location of the shell that is needed to interpret our script.

In shell scripting, we normally come across two types of variables: system variables and user defined variables. SHELL is one such system variable. Other commonly used system variables are PWD, PATH, USERNAME, HOME etc. And we normally use three types of quotes while writing a shell script…

a. Double quote
b. Single quote
c. Back quote

For example, ‘echo “Today is a good day” ’ will display ‘Today is a good day’ as its output, while ‘echo “Today is `date`” ’ will display the following output:
[sourcecode language=”bash”][root@localhost ~]# ./
Today is Mon Jun 21 05:03:47 EDT 2010
Please note that the contents of script looks like this:
[sourcecode language=”bash”][root@localhost ~]# cat
echo “Today is `date`”
Let us have a look at some of shell scripting fundamentals…

a. Redirection
b. Variables
c. Arithmetic expansions
d. Control constructs

As we all know, by default, a command accepts input from standard input (referred to as stdin) and directs its output to standard output (abbreviated as stdout). In some cases, we may want a command to receive input from somewhere other than the stdin and display its output to somewhere other than the stdout. This can be accomplished by using the redirection concept.
For example, ‘ls > file1’ will redirect the output of the ls command (ie listing of files and directories) to a file named ‘file1’.
If we want to append the date to the end of a file, we can go for the following command:
[sourcecode language=”bash”]date >> file1
Pipelining is another form of redirection. This is used to chain commands so that one can construct more powerful ones. The pipe symbol takes the output from the command preceding it and redirects it to the command following it.

twitter follow us
Pages: 1 2 3 4 5 6
  • Tell a Friend
  • Follow our Twitter to find out about all the latest Linux news, reviews, previews, interviews, features and a whole more.