4.4.5 How do I write a simple shell script?
Create a text (ASCII) file which will contain the shell script. For example, I would use the pico editor to write a script that runs the program tar with all the parameters usually necessary to uncompress tarballs downloaded from the Internet (I never seem to remember the tar options). I decided to call my script "untar":
Since the file "untar" did not exist in my current directory, it was created by the pico text editor. Now, I type in the content of my script:
echo this is the script file $0
echo untarring the file $1
# this calls tar with options -xvzf (extract,
# verbose, filter through gzip, input filename)
tar -xvzf $1
I save the file with <Ctrl>o and exit with <Ctrl>x
The first line of the script, starting with "#!" (called pound-bang), is special--it tells the shell what program should be used to interpret my script. In this example, the script is to be interpreted by the bash shell /bin/bash . The first line must start with #! or the script will never run (the file will be interpreted as just a text file). Other lines starting with # are comments for the author (readers, users) of the shell and are totally ignored by the computer.
The $0, $1, $2 ... in my script are the parameters passed to my script. For example, if I ran a script called "myscript" with seven parameters like this:
myscript a b c d e f g
then $0 would be seen inside "myscript" as having the value "myscript", $1 would have the value "a", $2 would be "b", $3 would be "c", etc.
On the second and third line of my example script, the command echo prints on the screen everything that follows on the same line, expanding $0 and $1 to the values of the parameters passed to the script. The fourth and fifth line contains a comment I wrote to myself to remind myself what I was trying to achieve, just in case I ever had to modify my script. The last line performs the actual work.
Once the script is written, I make the file executable to the file owner ("u"=user):
chmod u+x untar
and my script is ready to run like this:
Linux scripting is definitely rich, flexible, powerful and can be complex. However, it does not require special knowledge to write simple scripts for automation of common tasks. You just put together a group of often used commands, one by one, into a file. I use scripting because I am too lazy to type the same groups of commands over and over again.
A really simple sequence of commands can also be typed into a text file and passed to shell for straight execution using:
[No need for the initial "pound bang" or executable permission.]