Daniel Robbins President and CEO, Gentoo Technologies, Inc. 2000 How to use the Bash scripting language programming, will make Linux's daily interaction more interesting and productive, while you can also take advantage of those familiar and favorite standard UNIX concepts ( Such as pipes and redirects). In this three sections, Daniel Robbins will guide you with an example to program with BASH. He will tell very basic knowledge (this makes this series very suitable for beginners) and gradually introduces more advanced features in the subsequent series.
You may have to ask: Why do you want to learn Bash programming? Ok, here is a few convincing reasons:
Already running it If you can find it: You are now running Bash. Because Bash is a standard Linux shell and is used for a variety of purposes, so even if the default shell is changed, Bash may still run some of the system. Because Bash is already running, any Bash script running in the future is healthy use of memory because they share memory with any running Bash process. If you are running, you can work, and do it very well, why also put it into a 500K interpreter?
It is already using it not only running Bash, in fact, you are still dealing with BASH a day. It is always there, so learning how to use it to use it. This will make your Bash experience more interesting and productive. But why do you want to learn Bash programming? It is very simple, because you have already considered how to run commands, CPING files, and pipeline and redirect outputs. Why don't you learn a language in order to use and use the concepts of those who are familiar with and love? The command shell has enabled the potential of the UNIX system, and BASH is this Linux Shell. It is a high-end link between you and the machine. Grow Bash Knowledge, which will automatically improve productivity in Linux and UNIX - that is so simple.
Bash confused by mistakes Bash is very confused. Many newcomers entered "Man Bash" to view the Bash Help page, but only get very simple and technical shell functional descriptions. Someone enters "INFO BASH" (to view the GNU information document), can only get the resold page, or (if lucky) is a friendly information document.
Although this may make the beginners disappointed, the standard Bash documentation cannot meet the requirements of everyone, it is only suitable for those who are generally familiar with shell programming. There are still many excellent technical information in the help page, but the help of beginners is limited.
This is the purpose of this series. In this series, I will tell how to actually use the Bash programming concept to write your own script. Unlike technical description, I will explain to you in a simple language, so that you don't know what things do, you know when you should use. At the end of this three series, you will be able to write complex Bash scripts yourself and use BASH and use BASH and to add knowledge by reading (and understanding) standard Bash documents. let's start.
Environmental Variables In Bash and almost all other shells, users can define environment variables that store them in ASCII string. The most convenient environmental variable is that they are the standard part of the UNIX process model. This means that environment variables are not only used by shell scripts, but also by compiled standard programs. When "Export" environment variables in Bash, any program running later, no matter whether it is a shell script, you can read the settings. A good example is the vipw command, which usually allows the root user to edit the system password file. By setting the Editor environment variable into a favorite text editor name, you can configure the VIPW to make it use the editor, without using VI, if you are accustomed to Xemacs, you don't like VI, then this is convenient. The standard method for defining environment variables in Bash is:
$ myvar = 'this is my environment variable!'
The above command defines a environment variable named "MyVar" and contains strings "this is my environment variable!". There are some precautions above: First, there is no space on both sides of the equal sign "=", and any space will result in an error (try to see). The second part should pay attention to: Although the quotation marks can be omitted when defining a word, the quotation marks are required when the defined environment variable value is more than one word (including spaces or tabs).
Quote Details For very detailed information on how to use quotes in Bash, see the "Reference" section in the Bash Help page. Special character sequences are made complicated by other values "extended" (replace) indeed make the processing of strings in Bash. This series will only describe the most common reference functions.
Third, although it is usually used to replace single quotes, in the above example, this will result in an error. why? Because single quotes are disabled, the Bash feature called extended is disabled, where special characters and character series are replaced by a value. For example, "!" Characters are historical extensions characters, BASH usually replaces them with commands previously entered. (Historical extensions will not be described in this series, as it is not commonly used in Bash programming. For more information on historical extensions, see the "Historical Extensions" section in the Bash Help page.) Although this is similar to the macro Convenient, but now we only want to add a simple exclamation point behind the environment variable, not a macro.
Now let's take a look at how actually use environment variables. This has an example:
$ Echo $ MyVar
This is my environment variable!
Based by adding one $ in front of the environment variable, Bash can replace it with myvar's value. This is called "variable extension" in Bash terms. But what will this be:
$ echo foo $ myvarbar
foo
We hope to look back "Foothis is my environment variable! Bar", but not this. Where is wrong? Simply put, Bash variable extension facilities have been confused. It can't identify which variable to expand: $ m, $ my, $ myvar, $ myvarbar, etc. How do I clearly tell which variables? Try this:
$ echo foo $ {myvar} bar
Foothis is my environment variable! bar
As you can see, when the environment variable is not clearly separated from the surrounding text, it can be enclosed with the curneth. Although $ MyVar can be entered faster, it works correctly in most cases, but $ {myvar} can be correctly analyzed in almost all situations. In addition, the two are the same as the remainder of this series will be seen in the remainder of this series. Keep in mind: When the environment variable does not use blank (spaces or tabtles) to separate the surrounding text, please use a more clear curly parentheses. Recall that we also mentioned that "export" variables can be "exported. When the environment variable is exported, it can automatically use any scripts or executable program environments running later. The shell script can use the shell's built-in environment variable to support the "arrival" environment variable, and the C program can be called using the GetENV () function. Here are some C code examples, input and compile them - it will help us understand environment variables from the angle:
MyVar.c - Sample Environment Variable C Program
#include
#include
INT main (void) {
Char * myenvvar = getenv ("editor");
Printf ("The Editor Environment Variable IS Set TO% S / N", MyEnvvar;
}
Save the above code to file myenv.c, then issue the following command to compile:
$ gcc myenv.c -o myenv
Now, there will be an executable program that will print the value of the Editor environment variable at runtime (if worthless). This is when running on my machine:
$ ./myenv
The Editor Environment Variable IS Set To (NULL)
Ah ... Because the Editor environment variable is not set to any value, the C program gets an empty string. Let's try to set it to a specific value:
$ Editor = Xemacs
$ ./myenv
The Editor Environment Variable IS Set To (NULL)
Although I hope Myenv printed "Xemacs", but because there is no export environment variable, it is not working very well. This time makes it work correctly:
$ export editor
$ ./myenv
The Editor Environment Variable Is Set To Xemacs
Now, if you see it in your own: Do not export environment variables, another process (in this example C program) does not see environment variables. By the way, if you want, you can define and export environment variables in a row, as shown below:
$ export editor = Xemacs
This is the same as the two versions of the version. Now this demonstrates how to use unset to remove environment variables:
$ unset editor
$ ./myenv
The Editor Environment Variable IS Set To (NULL)
DirName and Basename Please note: DirName and BaseName are not files or directories on disk, they are just string operation commands.
Truncating String Overview The truncated string is a separate block that cuts the initial string into a smaller block, which is one of the typical tasks per day. Many times, the shell script needs to use a fully qualified path and find the ended file or directory. Although it can be implemented with Bash encoding (and interest), the standard BaseName Unix executable can do this: $ basename /usr/local/share/doc/foo/foo.txt
FOO.TXT
$ basename / usr / home / drobbins
DROBBINS
BaseName is a minus tool for a string string. Its related command DIRNAME returns a "other" part of BaseName discarded.
$ dirname /usr/local/share/doc/foo/foo.txt
/ usr / local / share / doc / foo
$ DIRNAME / USR / HOME / DROBBINS /
/ usr / home
Command Replacement requires a simple operation: How to create a environment variable containing the result of executable command. This is easy:
$ MyDir = `Dirname / usr / local / share / doc / foo / foo.txt`
$ Echo $ MyDir
/ usr / local / share / doc / foo
The above is called "command replacement". There is a need to point out in this case. In the first line, the command to be executed simply enclose the command to be executed. That is not a standard single quotes, but the single quotes typically located on the Tab key in the keyboard. You can use the Bash alternate command to replace the syntax to do the same thing:
$ MyDir = $ (DirName /usR/local/share/doc/foo/foo.txt)
$ Echo $ MyDir
/ usr / local / share / doc / foo
As you can see, Bash provides a variety of ways to perform exactly the same operation. Use the command replacement to place any commands or command pipes between `` or $ () and assign it to the environment variable. Really convenient! Here is an example that demonstrates how to use pipes in command replacement:
MyFiles = $ (LS / ETC | GREP PA)
Bash-2.03 $ Echo $ MyFiles
Pam.d Passwd
As professional, the string is truncated, although BaseName and Dirname are very good tools, but sometimes you may need to perform a higher string "truncation", not just a standard path name operation. When a stronger persuasion is required, the BASH built-in variable extension function can be used. Variable extensions similar to $ {myvar} have been used. But Bash itself can also perform some convenient string truncation. Look at these examples:
$ Myvar = foodforthought.jpg
$ Echo $ {MYVAR ## * fo}
Rthought.jpg
$ Echo $ {myvar # * fo}
Odforthought.jpg
In the first example, the $ {myvar ## * fo} is entered. What is its exact meaning? Basically, enter the environment variable name in $ {}, two ##, then the wildcard ("* fo"). Then, BASH gets myvar, find the beginning of the start of the string "FoodfortHought.jpg", and match the wildcard "* fo", and then cut it from the beginning of the string. There will be some difficulties when I start understanding, in order to feel how this special "##" option works, let's take a step in see how Bash completed this extension. First, search from the "* fo" wildcard matching sub-string from the beginning of "foodforthought.jpg". The following is a sub-string checking: f
Fo matches * fo
foo
Food
FooDF
FooDfo matches * fo
FooDfor
FooDfort
FooDforth
FooDfortho
FooDforthou
FooDforthoug
Foodforthought
Foodforthough.j
Foodforthought.jp
Foodforthought.jpg
After searching the matching string, you can see that BASH finds two matching. It chooses the longest match, removes from the beginning of the initial string, and then returns the result.
The second variable extension shown above appears to be the same as the first one, but it only uses one "#" - and Bash executes almost the same process. It looks through the same sub-string series as the first example, but Bash removes the shortest match from the initial string, and then returns the result. So, check the "FO" sub-string, which removes "fo" from the string, and then returns "odforthought.jpg".
This is said that it may be very confused, and this is remembered in a simple manner. When searching for the longest match, use ## (because ## ratio # long). When searching for the shortest match, use #. Look, not difficult! Wait, how to remember that the '#' character should be used to remove from the start of the string? Very simple! Notice: On the US keyboard, Shift-4 is "$", it is a Bash variable extension character. On the keyboard, close to the left of "$" is "#". In this way, you can see that "#" is "$" "Start", so ("#" is removed from the beginning of the string (based on our memory method). You may have to ask: How to remove characters from the end of the string end. If we guessed the characters we close against "$" on the US keyboard ("%), then there are some simple examples to explain how to cut the end of the string:
$ Myfoo = "chickensoup.tar.gz"
$ Echo $ {myfoo %%. *}
Chickensoup
$ ECHO $ {Myfoo%. *}
Chickensoup.tar
As you can see, in addition to removing matching wildcards from the end of the string,% and %% variable extensions are the same as # and ## work. Please note: If you want to remove a specific subrout string from the end, you don't have to use the "*" character:
Myfood = "Chickensoup" $ Echo $ {Myfood %% Soup}
Chicken
In this example, use "%%" or "%" is not important because there can be only one match. Also remember: If you forget to use "#" or "%", look at the 3, 4 and 5 keys on the keyboard, then guess.
You can select a specific sub-string using another form of variable extension based on a particular character offset and length. Try to enter the following line in BASH:
$ EXCLAIM = COWABUNGA
$ Echo $ {EXCLAIM: 0: 3}
Cow
$ Echo $ {EXCLAIM: 3: 7}
Abunga
This form of string is very simple, simply separates the starting character and sub-string length with a colon.
Applying string truncation Now we have learned all the knowledge of all truncation strings, and write a simple short shell script. Our script will accept a file as an argument, then print: This file is a TAR file. To determine if it is a tar file, look up mode ".tar" at the end of the file. As follows:
mytar.sh - a simple script
#! / bin / bash
IF ["$ {1 ## *.}" = "TAR"]
THEN
Echo this Appears to be a tarball.
Else
Echo at First Glance, This Does Not Appear To Be a Tarball.
Fi
To run this script, enter it into the file mytar.sh, then enter "ChMOD 755 MyTar.sh" to generate an executable. Then, do the TAR file trial as follows:
$ ./mytar.sh thisfile.tar
This Appears to be a tarball.
$ ./mytar.sh Thatfile.gz
At First Glance, this Does Not Appear To Be a Tarball.
Ok, successfully run, but it is not practical. Let's take a look at the "IF" statement used above before making it more practical. A Boolean expression is used in the statement. In Bash, "=" compares operators check whether the string is equal. In Bash, all Boolean expressions are enclosed in square brackets. But what is the Boolean expression actually test? Let us look at the left. The "$ {1 ## *.}" Will remove the longest "*." Match from the string start portion of the environment variable "1", and return the result. This will return all parts after the last ".". Obviously, if the file ends with ".tar", the result will be "TAR", the conditions are true.
You may think: What is the "1" environment variable starting everywhere. Very simple - $ 1 is the first command line of the password to the script, $ 2 is the second, and so on. Ok, it has been reviewed, and the "IF" statement is pretended to.
The IF statement is the same as most languages, BASH has its own conditions. In use, you must follow the above format; ie, "if" and "" "are placed in different rows and align the" fi "necessary to" else "and the end. This will make the code easy to read and debug. In addition to "if, else" form, there are other forms of "if" statement: if [consition]
THEN
Action
Fi
This statement is only executed when the condition is true, otherwise the operation is not executed, and "Fi" will continue.
IF [Condition]
THEN
Action
Elif [Condition2]
THEN
Action2
.
.
.
Elif [Condition3]
THEN
Else
ActionX
Fi
The above "ELIF" form will continue to test each condition and perform operations that meet the first true condition. If there is no condition is true, the "ELSE" action will be executed. If there is a condition true, continue to perform the entire "IF, Elif, Else" statement.
Next time we have learned the most basic Bash function, now you have to speed up your footsteps, ready to write some actual scripts. In the next article, the loop concept, function, name space, and other important topics will be described. Then, you will be ready to write some more complex scripts. In the third article, you will focus on some very complex scripts and features, as well as several Bash script design options. Goodbye!
Reference
Visit the GNU's Bash Homepage Bash Online Reference Manual
Transfer from: IBM DeveloperWorks China website