Synfire's Quick Guide to Linux

Shell Scripts

Introduction to Shell Scripts

The scripting language we will be using is the Bourne Again Shell, or Bash Scripting. I chose this language because I like bash, I use bash, and I recommend bash. Shell Scripting is an important skill when it comes to Linux, or any UNIX based operating system, because it automates tasks and helps you to create some pretty kewl, program like, scripts.

Creating and Running Shell Scripts

Basically, to create a shell script you open up vi and place the commands you want the shell to execute in the text file. Then you place an exec call to the interpreter on the first line. After that you save the file and at the terminal call chmod +x to make the file executable. To some of you that may sound a bit technical but it really isn't! I will break this down with an example script:
#!/bin/bash  # This is the interpreter it is located at '/bin/bash'
         # The first line will be in all bash scripts
         # if you were writing a tcsh script it would be
         # represented by '#!/bin/tcsh'
         
# remount.sh - This script remounts the floppy drive
# This is a comment prompt, comments are overlooked by the interpreter
# and are only used to make modifiying files easier.
      
umount /mnt/floppy  # This part unmounts the floppy drive

mount /mnt/floppy   # This part mounts the floppy drive

Now that we have written this file in vi save the file as remount.sh.

Now type ':wqa' to save and exit. Now at the command prompt type:
root@localhost /]# chmod a+x remount.sh
This will make remount.sh executable. Now you should place this file in the /bin directory, do so by typing:
root@localhost /]# mv remount.sh /bin
Now all there is left to do is execute the script by typing its name in the command prompt like so:
root@localhost /]# remount.sh
Congratulations, you have just written and executed your first shell script.

The basic usage for this is that on some versions of linux you have to unmount and re-mount the floppy and cdrom drives everytime you change a disk. Now instead of typing two lines of code each time you change disks you just insert the new disk and type 'remount.sh'. Another way to execute the shell script without having to move them all to the /bin directory is with the use of your shells execute command. If you use bash, wich I recommend you do, you would use the 'dot' command:

root@localhost /]# . remount

tcsh users type:

root@localhost /]# source remount
The number of programs you can execute in a shell script is unlimited you could create a shell script just to execute one or two commands or you could create one to do a thousand commands it's all up to you.

Variables

In this next section, you will learn about one of the most useful tools in any programming/scripting language... VARIABLES.

I'm sure if you are old enough to read this document you surely have dealt with variables in math class (ie. x+2=5 x=__ ?) Now to set a value to a variable you simply type the variable name followed by and equals sign followed by the value:
name=Jack
age=22
Note in the example that the variable can hold strings (alphabetical characters) or integers (numerical values). Also note that when assigning a variable there are no spaces on either side of the equals.

** I can't stress enough that this is bash scripting, other scripting languages such as tcsh, csh, zsh, or pdksh use a different syntax **

Now that we have stored our information into the variables how do we get this information back out? Easy! Just preceed the variable with a $ sign. The following example will print the 'name' variable assigned earlier to the terminal screen:
echo $name
The output during execution would be:
root@localhost /]# 
Jack
root@localhost /]#
Now what if you wanted to pass arguments from the command line into the shell script? Thats not so hard either! All shell interpreters have special variables that read from the command line. These variables are called 'positional parameters'. Here is an example of the remount program that lets you choose the device you would like to remount.
#!/bin/bash

# remount - Advanded remount program

umount $1
mount $1
Now you can execute this with either 'remount /mnt/floppy' or 'remount /mnt/cdrom' and the file would still work. Now a Positional parameters variable is a number 1-9 the number 1 is the first argument the number 2 is the second and so on. There are many more built in variables a shell environment has. Here is a list of these:
Variable                Description
$# .................... Stores the number of command-line arguments passed
$? .................... Store the exit value of the last executed command
$* .................... Stores all the arguments on the command-line
$@ .................... Stores all the arguments on the command-line,
                        individually double-quoted
$0 .................... Holds the name of the shell script (ie. remount)
$LOGNAME .............. Holds the username of the current user
The Significance of Quotes

The types of quotes you use are very important. There are two types of quotes, single ('') and double (""). Double quotes are the least powerful of the two. It hides whitespaces but all other special characters are still interpreted by the shell. This is expecially good for sting values with more than one word:

name="Jack Ripper"
This sets both Jack and Ripper to be assigned as though the space was a letter. If you typed:
name=Jack Ripper
The interpreter wouldn't understand and would return and error. Single quotes are the more powerful of the two. They assign exactlly what is inputed. lets take a look at the difference:
fname=Jack
lname=Ripper

flcone="$fname $lname"
flctwo='$fname $lname'

echo "$flcone is in double-quotes"
echo "$flctwo is in single-quotes"
Now when executed you can see what the difference is:
root@localhost /]# . double-single_test.sh
Jack Ripper is in double-quotes
$fname $lname is in single-quotes
root@localhost /]#
Notice that the single-quotes did not interpret the variables, instead wrote the variable names to the screen. Now you have learned about how quotes hide special characters from the interpreter, but there is another tool used called backslash. Here is a comparison of the double-quote name and the back- slash name:
(using double-quotes)

name="Jack Ripper"

(using backslash)

name=Jack\ Ripper
Both of these have the same meaning just written differently. The main usage of the backslash character is to hide posible functions from the shell:
price=\$100.00

This example keeps price from being assigned the first argument on the command line, lets say you added the number 3 as the first argument of this script any you didn't add the backslash. The value of 'price' would be changed to 300.00 instead of $100.00 (understand?).

Another quote is the back-quote (``). This is use when you want to place the output of a command into a variable. So if you wanted to store the output of who into a variable named vwho, you would do this:
vwho=`who`

I will end this section with a small script called greetings.sh:
#!/bin/bash

# greetings.sh - prints a degrating message to the current user.

me=`whoami`
amount=\$0.01
$mom='$0.01'
echo "$me is worth $amount, that's $mom more than what I payed for $me 's Mom!"
The Test Command

The test command is use to evaluate truth of an expression. There are two ways to write a test, but, I will focus mainly on just one of them. They are:

test expression
or
[ expression ]

Our main focus will be on the last one because when scripting this makes your program look more like a program than just a list of commands. You will see what I'm talking about later on in the next few chapters.

The expressions are evaluated as true of false. This is done with the use of operators. There are four types of operators, and they are: integer, string, file, and logical. Here is a list of each of these:
Table 1.1
Integer Operators
+----------------------------------------------------------------------------+
|      Operator      |  Definition                                           |
+----------------------------------------------------------------------------+
|   expr1 -eq expr2  |  Returns True if expr1 is equal to expr2              |
+----------------------------------------------------------------------------+
|   expr1 -ge expr2  |  Returns True if expr1 is greater than or equal to    |
|                    |  expr2                                                |
+----------------------------------------------------------------------------+
|   expr1 -gt expr2  |  Returns True if expr1 is greater than expr2          |
+----------------------------------------------------------------------------+
|   expr1 -le expr2  |  Returns True if expr1 is less than or equal to expr2 |
+----------------------------------------------------------------------------+
|   expr1 -lt expr2  |  Returns True if expr1 is less than expr2             |
+----------------------------------------------------------------------------+
|   expr1 -ne expr2  |  Returns True if expr1 does NOT equal expr2           |
+----------------------------------------------------------------------------+
Table 1.2
String Operators
+----------------------------------------------------------------------------+
|      Operator      |  Definition                                           |
+----------------------------------------------------------------------------+
|     str1 = str2    |  Returns True if str1 is identical to str2            |
+----------------------------------------------------------------------------+
|     str1 != str2   |  Returns True if str1 is not identical to str2        |
+----------------------------------------------------------------------------+
|      -n str        |  Returns True if the length of str is greater than    |
|                    |  zero                                                 |
+----------------------------------------------------------------------------+
|      -z str        |  Returns True if the length of str is equal to zero   |
+----------------------------------------------------------------------------+
|       str          |  str in a Test command without any other operators    |
|                    |  returns True if str is not equal to NULL             |
+----------------------------------------------------------------------------+
Table 1.3
File Operators
+----------------------------------------------------------------------------+
|      Operator      |  Definition                                           |
+----------------------------------------------------------------------------+
|     -d filename    |  Returns True if filename is a directory              |
+----------------------------------------------------------------------------+
|     -f filename    |  Returns True if filename is a file                   |
+----------------------------------------------------------------------------+
|     -r filename    |  Returns True if filename can be read                 |
+----------------------------------------------------------------------------+
|     -s filename    |  Returns True if filename has a non-zero length       |
+----------------------------------------------------------------------------+
|     -w filename    |  Returns True if filename can be written to           |
+----------------------------------------------------------------------------+
|     -x filename    |  Returns True if filename is executable               |
+----------------------------------------------------------------------------+
Table 1.4
Logical Operators
+----------------------------------------------------------------------------+
|     Operator       |  Definition                                           |
+----------------------------------------------------------------------------+
|   ! expression     |  Returns True if expression is false                  |
+----------------------------------------------------------------------------+
|    exprA -a exprB  |  Returns True if exprA and exprB are both true        |
+----------------------------------------------------------------------------+
|    exprA -o exprB  |  Returns True if exprA or exprB is true               |
+----------------------------------------------------------------------------+

< < < Lesson 3: vi & vm | Lesson 4.2: Shell Scripts part 2 > > >



Have Linux and want to learn more or just fancy trying it? Read our Linux tutorial.