Open Source

Using the bash command line

Need to get familiar with the fundamentals of the Linux <I>bash</I> command line and the Linux shell? In this Daily Drill Down, Dallas Releford explains these topics plus conditional statements, iteration statements, and variables.


In this Daily Drill Down, I’ll attempt to familiarize you with the fundamentals of the Linux bash command line and the Linux shell. I’ll also give examples of shell script files and how to use conditional and iteration statements.

What is the Linux shell?
The shell is another name for the command interpreter that gives you the command prompt when you first run the operating system. It also accepts and responds to anything that you type at the prompt and tells the computer to follow your instructions and commands. In DOS, this function is controlled by Command.com. If you’re familiar with the DOS shell, then you’re one step closer toward knowing how the Linux command interpreter, or shell, works. A Linux shell such as bash is both a command interpreter and a programming language.

A shell is simply a macro processor that executes commands that are entered at the command prompt or from a text-based script file. In Linux, the shell is the first program that runs when you log in, and it runs until you log out of the system. Linux is capable of running several shells, but the default shell is called bash, and it’s probably the most used. When you use shell, you normally enter commands one at a time.

Although bash is usually the default shell, if you want to see if bash is running on your system, then enter this at the command prompt:
echo $BASH_VERSION

What are shell script files?
A Linux shell script is similar to a DOS batch file. You can put the commands in the shell script, compile the script file, and then run it. You can create shell script files with just about any text editor, such as vi or emacs.

After you’ve programmed all of your commands into the shell script file, you must compile or make the script file ready for execution by using the chmod command.

Let's say you’ve created a file called Friday, which runs your backups on Friday. Here’s how to make it executable:
chmod +x Friday

After you’ve made the file executable, you can run it just like you would any other Linux command. To make the file executable, you must make sure that it’s in the search path. To get the search path, type the following:
echo $PATH

If the file directory is not in the search path, then you’ll have to add the directory. To execute the program once you’ve established where the search path is, simply type:
Friday

If you want to use a particular shell to run your program, you must enter the name of the shell followed by the name of the file like in the example below:
bash Friday

What does a shell script file look like?
This is a simple shell script file that displays some information about you and your computer:
echo "Date and time is:"
date
echo "Your username is:"
whoami
echo "Your current directory is:"
pwd
echo "Files in this directory will \
be listed in the file 'file_listing':"
ls > file_listing


The first four lines are simply comment lines. You begin your comments with the hash (#) sign so that bash can recognize the hash. The shell will ignore anything that begins with a hash.

The lines beginning with echo will literally echo onto the screen what is in double quotes. The lines after the echo line (all one word—or command—lines) are the actual commands that perform the actions. As you can see, the last echo line is a bit long, so we add an escape character (the '\' character) that tells the shell that the line is continued to the next line.

One of the most useful features of programming is to be able to obtain information from the user. Here’s one way to do it using bash.

Using the read command in your shell script would look something like this:
echo "User Information
  Menu: "
echo "Enter your last
  name: "
read lname
echo "Enter your first
  name: "
read fname
echo "You can now log in
  $fname $lname"


The result will be something like the output below:
You can now log in Haversham Happenstance

In this example, the user is prompted for input, and the input is assigned to a variable name. When you want to display the contents of a variable in the shell scripting language, you must put a dollar sign ($) before it. The read command is used to get information from the user and is placed in the lname variable. The echo command simply prints what is stored in the variable. The fi command just means finished. By using this technique, you can get information from your users, store it in variables, and print it out on the screen.

What are variables?
Every language must have some way of storing information, and most languages use some form of variable. The shell programming language has its own built-in variables such as PATH, PS1, and the positional parameters 1 and 2. You can also create your own customized variables. A variable is merely a place in memory that holds some value or information. You have to give the variable a name and assign it a value.

In the bash shell-scripting language, you can assign a value to a variable simply by typing the variable name followed by the equal sign and then giving it a value. For instance, if you wanted to create a variable called weekday and give it a value of 3 for Wednesday, then you would do this:
weekday=3

This saves a place in memory, names it weekday, and gives it a value of 3. In the following example,
fname=elizabeth

the fname variable stores the name elizabeth.

Now you have stored two kinds of information in the two variables. A numerical value is stored in the weekday variable. In the fname variable, we’ve stored alphabetical information. How do you get the information out in order to use it once you’ve put it there? Simply type echo and then the variable name, like this:
echo $weekday or echo $fname

Variables can be very useful for storing and retrieving information. You must be careful not to use the same variable name for two different values in the same scripting program. Give each variable a name that means something to you and to others who may be using your program.

What are conditional statements?
The bash, pdksh, and the tcsh shells have two kinds of conditional statements. These are the if and case statements that are similar to the ones you’ve probably used in other languages such as BASIC. These two statements are used to execute different parts of the shell program depending on whether certain conditions are true. The syntax is a little different between the various shells, so rather than try to cover all of them, we’ll use bash and pdksh for our examples.

The if statement
The conditional if statements allow you to perform complicated conditional tests in your shell programs. The syntax of the if statement is as follows:
if [ expression ]
 then
 commands
elif [ expression2 ] (an abbreviation of the words else if)
 then
 commands
else
 commands
fi (used to signal the end of the if statement)


In the syntax as described above, the statement elif is executed only if none of the expressions associated with the if statement (or any elif statements before it) are true. The commands associated with the else statement are executed only if none of the expressions associated with the if statement or any of the elif statements are true.

The shell case statement
The case statement, as it applies to the shell, enables you to compare a condition with several other conditions and execute a block of code if a match is found. The correct syntax for bash and pdksh is as follows:
case string1 in
 str1)
 commands;;
 str2)
 commands;;
 *)
 commands;;
esac (indicator of termination)


In this syntax, we have string1 being compared to str1 and str2. If one of these strings matches string1, the commands up to the double semicolon are executed. But, if neither str1 nor str2 matches string1, the commands associated with the asterisk are executed.

The shell iteration statements
You have probably heard the word iteration if you’ve been around computers very long. It simply means to loop. The for statement is an iteration statement that’s most commonly used in not only shell languages but in most other languages, as well. The shell language provides many such statements, but for is probably the most widely used.

Using the for statement
The for statement will execute the commands that are contained within itself the number of times specified in the code statement. Both bash and pdksh have two variations of the for statement.

The first form of the for statement for bash and pdksh is shown in the following syntax:
For var1 in list
 Do
 Commands
 Done


The for statement executes one time for each item in the list. In this list, a variable can contain several words separated by spaces or a list of values that’s typed into the statement. Each time the loop is completed, the variable var1 will be assigned the current item in the list until the end of the loop is reached.

The second form has the following syntax:
for var1
 do
 statements
 done


The for statement will execute one time for each item in var1. When using this syntax of the for statement, the shell program assumes that the variable var1 contains all the positional parameters that were passed into the shell program on the command line. You must be careful when writing for loops in your programs, as they can go into what is called a continuous loop that will run forever.

Use of the for statements provides you with ways to repeat an operation or command without having to continually type something in or physically do something. In the following example, we’ll create a standard, simple program that uses the cat command to check to see who is on the system. The rest of the statement is pretty much self-explanatory. Notice that you should start each shell program with something like #!/bin/sh and heavily comment it so that you’ll know what it does the next time you may need to edit or change it. In the first line, cat simply displays the contents of the statuswho file:
cat statuswho
#!/bin/sh
# let's see who all is on the system
for i in $*
do
if who | grep -s $i > /dev/null
then
echo $i is logged in
else
echo $i not available
fi
done


To run this program, you would have to enter the command name followed by the user you are looking for. For example, if you wanted to see if Cartman was logged into your system, you would enter:
./test Cartman

If Cartman was logged in, you would see:
Cartman is logged in

If Cartman was not logged in, you would see:
Cartman not available

This is a nice little program that we can use whenever we want to see if someone else is on the system. You can try this if you work on a multiuser (network or mainframe) system or environment. Don't forget to use chmod to make the program executable.

Using the while statement
The while statement causes a block of code to be executed while a provided conditional expression is true. The syntax used by bash and pdksh is as follows:
while expression
 do
 statements
 done


The while statement is similar to the for statement. It will execute while a certain condition is true, or it will execute as long as a certain condition is true.

Using the until statement
The until statement is similar in syntax to the while statement. The only real difference between the two is that the until statement executes its code block while its conditional expression is false. The while statement executes its code while its conditional expression is true. In other words, the until statement will execute either until a certain condition is true or until a certain condition is false.
until expression
 do
 commands
 done


Creating and using functions in the Linux shell
A function is nothing more than a block of code that performs some specific task. Using functions in the Linux shell language is similar to using functions in any other language. Functions allow you to group common code together instead of scattering it throughout your program. These functions are advantageous because they make your code more organized, easier to read and maintain, and smaller in nature.

In bash, a function is created in the following way:
myname () {
 shell commands
}


After you’ve created the function, you can invoke it like this:
Myname [parm1 parm2 parm3 ...]

Please notice that you can pass any number of parameters to your function after you’ve created it. The function will see those parameters as positional parameters, similar to a shell program when you pass parameters on the command line. In the situation shown above, to invoke the function, you simply type in the function name followed by the list of parameters that you wish to pass to it.

A demonstration program
This is a simple but useful little shell script to show you how to use all of the statements and commands that I’ve discussed. Let's call the program systats.
#!/bin/sh  
# systats
# written by Dallas G. Releford
# 12/June/2000
# this is a modifiable program to show
# some system statistics
# you can add to it for more practical usage
# note that you should heavily document computer
# programs for your own good and everyone's sanity.
# beginning of actual first subprogram
# This script displays the date, time, username and
# current directory.
echo "Date and time is:"
date
echo "Your username is:" `whoami`
echo "Your current directory is:"
pwd
echo ``Show disk status''
du
echo ``Show memory usage''
free
echo ``List files on current directory''
ls
echo ``Check current running processes''
ps
echo ``View the Directory Structure''
tree
echo ``Information about me''
id
echo ``Check what system is running''
uname –a
echo ``Thats the end of the program - Please exit''


If you want to try this program, please remember to use the chmod command to compile it so that it can execute. The program tells you some things about your system. This is the type of utility script file that you’ll need to write to control how your computer works—or maybe just to let you know who else is using your system.

More about shell scripting
You can find a great bash online manual on the Official GNU site. You can also find the most current version of bash at this FTP site.

What to do next
There will probably be times when you use Linux that you’ll need to write shell scripts to control some action that you want to perform when the system starts up. The way to learn this is to read all that you can about bash and shell scripting. And the best way to learn it well is by doing it.

Editor's Picks

Free Newsletters, In your Inbox