热门关键字:  ubuntu  分区  函数  Fedora  linux系统进程

当前位置 :| 主页>Linux教程>Shell开发>

INTRODUCTION TO BASH SHELL SCRIPTING

来源: 作者: 时间:2008-08-27 Tag: 点击:

INTRODUCTION TO BASH SHELL SCRIPTING: VERSION 1.2

Like all the shells available in Linux, the Bourne Again SHell is not only an excellent command line shell, but a scripting language in itself. Shell scripting, allows you to fully utilize the shell's abilities and to automate a lot of tasks that would otherwise require a lot of commands to perform. A lot of programs lying around your Linux box are shell scripts. If you are interested in learning how they work, or in modifying them, it is essential that you understand the bash syntax and semantics. In addition, by understanding the bash language, you will be able to write your own programs to do things exactly the way you want them done.
 

PROGRAMMING OR SCRIPTING?

People who are new to programming are generally confused as to what the difference is between a programming and scripting language. Programming languages are generally a lot more powerful and a lot faster than scripting languages. Examples of programming languages are C, C++, and Java. Programming languages generally start from source code (a text file containing instructions on how the final program is to be run) and are compiled (built) into an executable. This executable is not easily ported into different operating systems. For instance, if you were to write a C program in Linux, you would not be able to run that C program in a Windows 98 system. In order to do so, you would have to recompile the source code under the Windows 98 system. A scripting language also starts from source code, but is not compiled into an executable. Rather, an interpreter reads the instructions in the source file and executes each instruction. Unfortunately, because the interpreter has to read each instruction, interpreted programs are generally slower than compiled programs. The main advantage is that you can easily port the source file to any operating system and have it interpreted there right on the spot. bash is a scripting language. It is great for small programs, but if you are planning on doing major applications, a programming language might be more beneficial to you. Other examples of scripting languages are Perl, Lisp, and Tcl.
 

WHAT DO YOU NEED TO KNOW?

Writing your own shell scripts requires you to know the very basic everyday Linux commands. For example, you should know how to copy, move, create new files, etc. The one thing you must know how to do is to use a text editor. There are three major text editors in Linux, vi, emacs and pico. If you are not familiar with vi or emacs, go for pico or some other easy to use text editor.
 

WARNING!!!

Do not practice scripting as the root user! Anything could happen! I will not be held responsible if you accidentally make a mistake in the coding and screw up your system. You have been warned! Use a normal user account with no root privileges. You may even want to create a new user just for scripting practice. This way the worst thing that can happen is the user's directory gets blown away.
 

YOUR FIRST BASH PROGRAM

Our first program will be the classical "Hello World" program. Yes, if you have programmed before, you must be sick of this by now. However, this is traditional, and who am I to change tradition? The "Hello World" program simply prints the words "Hello World" to the screen. So fire up your text editor, and type the following inside it:


#!/bin/bash

echo "Hello World"
 

The first line tells Linux to use the bash interpreter to run this script. In this case, bash is in the /bin directory. If bash is in a different directory on your system, make the appropriate changes to the line. Explicitly specifying the interpreter is very important, so be sure you do it as it tells Linux which interpreter to use to run the instructions in the script. The next thing to do is to save the script. We will call it hello.sh. With that done, you need to make the script executable:
 

xconsole$ chmod 700 ./hello.sh
 

Refer to the manual page for chmod if you do not know how to change permissions for a file. Once this is done, you will be able to run your program just by typing its name:
 

xconsole$ ./hello.sh
Hello World
 

There it is! Your first program! Boring and useless as it is, this is how everyone starts out. Just remember the process here. Write the code, save the file, and make it executable with chmod.
 

COMMANDS, COMMANDS, COMMANDS

What exactly did your first program do? It printed the words "Hello World" to the screen. But how did it do that? It used commands. The only line of code you wrote in the program was echo "Hello World". Well, which one is the command? echo. The echo program takes one argument and prints that argument to the screen.

An argument is anything that follows after you type the program name. In this case, "Hello World" was the argument that you passed to echo When you type the command ls /home/root, the argument to ls is /home/root. So what does this all mean? It means that if you have a program that takes an argument and prints it to the screen, you can use that instead of using echo. Let us assume that we have a program called foo This program will take a single argument, a string of words, and print them to the screen. We can rewrite our program as such:
 

#!/bin/bash
foo "Hello World"

Save it and chmod it and then run it:

xconsole$ ./hello
Hello World
 

The exact same result. Was there any unique code at all? No. Did you really write anything? Not unless you are the author of the echo program. All you did, was to embed the echo program into your shell program, with a argument already given. A real world example of an alternative to the echo command is the printf command. printf offers more control, especially if you are familiar with C programming. In fact, the exact same result could have been done without making a shell program:
 

xconsole$ echo "Hello World"
Hello World
 

bash shell scripting offers a wide variety of control and is easy to learn. As you have just seen, you use Linux commands to write your shell programs with. Your shell program is a collection of other programs, specially put together to perform a task.
 

A MORE USEFUL PROGRAM

We will write a program that will move all files into a directory, and then delete the directory along with its contents, and then recreate the directory. This can be done with the following commands:
 

xconsole$ mkdir trash
xconsole$ mv * trash
xconsole$ rm -rf trash
xconsole$ mkdir trash
 

Instead of having to type all that interactively on the shell, write a shell program instead:
 

#!/bin/bash
mkdir trash
mv * trash
rm -rf trash
mkdir trash
echo "Deleted all files!"
 

Save it as clean.sh and now all you have to do is to run clean.sh and it moves all files to a directory, deletes them, recreates the directory, and even prints a message telling you that it successfully deleted all files. So remember, if you find that you are doing something that takes a while to type over and over again, consider automating it with a shell program.
 

COMMENTS

Comments help to make your code more readable. They do not affect the output of your program. They are specially made for you to read. All comments in bash begin with the hash symbol: "#", except for the first line (#!/bin/bash). The first line is not a comment. Any lines after the first line that begin with a "#" is a comment. Take the following piece of code:
 

#!/bin/bash
# this program counts from 1 to 10:
for i in 1 2 3 4 5 6 7 8 9 10; do
    echo $i
done
 

Even if you do not know bash scripting, you immediately know what the above program does, because of the comment. It is good practice to make use of comments. You will find that if you need to maintain your programs in the future, having comments will make things easier.
 

VARIABLES

Variables are basically "boxes" that hold values. You will want to create variables for many reasons. You will need it to hold user input, arguments, or numerical values. Take for instance the following piece of code:
 

#!/bin/bash
x=12
echo "The value of variable x is $x"
 

What you have done here, is to give x the value of 12. The line echo "The value of variable x is $x" prints the current value of x. When you define a variable, it must not have any whitespace in between the assignment operator: "=". Here is the syntax:
 

variable_name=this_value
 

The values of variables can be accessed by prefixing the variable name with a dollar symbol: "$". As in the above, we access the value of x by using echo $x.

There are two types of variables. Local variables, and environmental variables. Environmental variables are set by the system and can usually be found by using the env command. Environmental variables hold special values. For instance, if you type:
 

xconsole$ echo $SHELL
/bin/bash
 

You get the name of the shell you are currently running. Environmental variables are defined in /etc/profile and ~/.bash_profile. The echo command is good for checking the current value of a variable, environmental, or local. If you are still having problems understanding why we need variables, here is a good example:
 

#!/bin/bash
echo "The value of x is 12."
echo "I have 12 pencils."
echo "He told me that the value of x is 12."
echo "I am 12 years old."
echo "How come the value of x is 12?"
 

Okay, now suppose you decide that you want the value of x to be 8 instead of 12. What do you do? You have to change all the lines of code where it says that x is 12. But wait... there are other lines of code with the number 12. Should you change those too? No, because they are not associated with x. Confusing right? Now, here is the same example, only it is using variables:
 

#!/bin/bash
x=12     # assign the value 12 to variable x
echo "The value of x is $x."
echo "I have 12 pencils."
echo "He told me that the value of x is $x."
echo "I am 12 years old."
echo "How come the value of x is $x?"
 

Here, we see that $x will print the current value of variable x, which is 12. So now, if you wanted to change the value of x to 8, all you have to do, is to change the line x=12 to x=8, and the program will automatically change all the lines with $x to show 8, instead of 12. The other lines will be unaffected. Variables have other important uses as well, as you will see later on.
 

CONTROL STRUCTURES

Control structures allow your program to make decisions and to make them more compact. More importantly as well, it allows us to check for errors. So far, all we have done is write programs that start from the top, and go all the way to the bottom until there are no more commands left in the program to run. For instance:
 

#!/bin/bash
cp /etc/foo .
echo "Done."
 

This little shell program, call it bar.sh, copies a file called /etc/foo into the current directory and prints "Done" to the screen. This program will work, under one condition. You must have a file called /etc/foo. Otherwise here is what happens:

最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册