Bash instance (1)

Source: Internet
Author: User
Article title: Bash instance (1 ). Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
Learning how to program with the bash scripting language will make daily Linux interactions more interesting and productive, while also taking advantage of the familiar and popular standard UNIX concepts (such as pipelines and redirection ). In this three-part series, Daniel Robbins provides an example of how to program using bash. He will describe very basic knowledge (which makes this series very suitable for beginners) and introduce more advanced features in subsequent series.
You may ask: why do you want to learn Bash programming? Well, here are some compelling reasons:
It is already running
You may find that you are currently running bash. Bash is a standard Linux shell for various purposes, so bash may still run somewhere in the system even if the default shell is changed. Because bash is already running, any bash scripts that run in the future are naturally effective in using the memory because they share the memory with any running bash process. If the running tool is competent and well-performed, why should we load a 500 K interpreter?
It is already in use
Not only is bash running, but you are still dealing with bash every day. It is always there, so it makes sense to learn how to use it to the maximum extent. This will make your bash experience more interesting and productive. But why learning bash programming? It's easy because you are already thinking about how to run commands, CPing files, and pipeline and redirection output. Why don't you learn a language to use and use the powerful and time-saving concepts that you are already familiar with and love? The command shell opens the potential of the UNIX system, and bash is the Linux shell. It is a high-level bond between you and your machine. Increase bash knowledge, which will automatically increase your productivity in Linux and UNIX-that's simple.
Bash confusions
Learning bash in the wrong way is confusing. Many new users enter "man bash" to view the bash help page, but only get a very simple and technical shell functional description. Someone else enters "info bash" (To view the GNU information document) and can only get a help page that is re-displayed, or (if lucky) a slightly friendly information document.
Although this may disappoint beginners, the standard bash document cannot meet everyone's requirements. it is only suitable for those who are already familiar with shell programming. The help page does contain a lot of excellent technical information, but it does not help beginners.
This is the purpose of this series. In this series, I will show you how to actually use bash programming concepts to write your own scripts. Different from the technical description, I will explain it in a simple language so that you not only know what to do, but also when to use it. At the end of the three series, you will be able to write complex bash scripts on your own, use bash freely, and supplement your knowledge by reading (and understanding) Standard bash documents. Let's get started.
Environment variable
In bash and almost all other shells, you can define environment variables, which are stored in ASCII strings. Environment variables are the most convenient: they are the standard part of the UNIX process model. This means that environment variables are not only used exclusively by shell scripts, but can also be used by compiled standard programs. When "exporting" environment variables in bash, any program running in the future can read the settings, whether it is a shell script or not. 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 to the name of your favorite text EDITOR, you can configure vipw to use this EDITOR without using vi. if you are used to xemacs but do not like vi, this is very convenient.
The standard method for defining environment variables in bash is:
$ Myvar = 'This is my environment variable! '
The preceding command defines an environment variable named "myvar" and contains the string "This is my environment variable! ". Note: First, there is no space on both sides of the equal sign "=". any space will lead to an error (please try it ). The second thing to note is: Although quotation marks can be omitted when defining a word, when the defined environment variable value is more than one word (including space or tabulation key ), quotation marks are required.
Reference details
For more information about how to use quotation marks in bash, see the reference section on the bash help page. The special character sequence is expanded (replaced) by other values to make string processing complicated in bash. This series only describes the most common reference functions.
Third, although double quotation marks can usually be used to replace single quotation marks, in the above example, this will cause errors. Why? Because the bash feature called extension is disabled with single quotes, special characters and character series are replaced by values. For example ,"! "Is a history extension character. bash usually replaces it with the previous command. (Historical extensions are not described in this series, as they are not commonly used in bash programming. For more information about historical extensions, see the "historical extensions" section on the bash help page .) Although this macro-like function is very convenient, we only want to add a simple exclamation point after the environment variable, rather than a macro.
Now, let's take a look at how to actually use environment variables. Here is an example:
$ Echo $ myvar
This is my environment variable!
By adding $ to the front of the environment variable, bash can replace it with the value of myvar. This is called variable extension in bash ". However, what will happen in this way:
$ Echo foo $ myvarbar
Foo
We want to echo "fooThis is my environment variable! Bar ", but not like this. Where is the error? Simply put, the bash variable extension facility is in confusion. It cannot identify which variable to expand: $ m, $ my, $ myvar, $ myvarbar, and so on. How can we clearly tell which variable bash references? 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, you can enclose it with curly brackets. Although $ myvar can be input faster and work correctly in most cases, $ {myvar} can be correctly analyzed through syntax in almost all cases. In addition, the two are the same, and the two forms of variable extension will be seen in the rest of this series. Remember: When the environment variables are not separated from the surrounding text by spaces (or tabulation keys), use a more explicit curly brackets.
In retrospect, we also mentioned the possibility of "exporting" variables. When an environment variable is exported, it can be automatically used by any script or executable program environment that will run in the future. Shell scripts can use the built-in environment variables of shell to support "arrival" environment variables, while C programs can use the getenv () function to call. Here are some examples of C code, input and compile them -- it will help us understand the environment variables from the perspective of C:
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 the file myenv. c, and then issue the following command for compilation:
$ Gcc myenv. c-o myenv
Now there will be an executable program in the directory, which will print the EDITOR environment variable value at runtime (if there is a value ). This is the case 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, 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 you want myenv to print the value "xemacs", it does not work very well because the environment variable has not been exported. This time let it work correctly:
$ Export EDITOR
$./Myenv
The editor environment variable is set to xemacs
Now, as you can see with your own eyes: If you do not export environment variables, the other process (in this example, the sample C program) will not see the environment variables. By the way, if you want to, you can define and export the environment variables in one line, as shown below:
$ Export EDITOR = xemacs
This is the same as the two-line version. Now we will demonstrate how to use unset to remove environment variables:
$ Unset EDITOR
$./Myenv
The editor environment variable is set to (null)
Dirname and basename
Note: dirname and basename are not files or directories on the disk. they are only string operation commands.
Truncation string overview
Truncates an initial string to a smaller independent block. it is one of the daily tasks executed by a shell script. Most of the time, shell scripts need to use a fully qualified path and locate the final file or directory. Although it can be implemented using bash encoding (and interesting), the standard basename UNIX executable program can do this well:
$ Basename/usr/local/share/doc/foo/foo.txt
Foo.txt
$ Basename/usr/home/drobbins
Drobbins
Basename is an easy tool for truncating strings. Its related command dirname returns another part of the path discarded by basename.
$ Dirname/usr/local/share/doc/foo/foo.txt
/Usr/local/share/doc/foo
$ Dirname/usr/home/drobbins/
/Usr/home
Command replacement
You need to know a simple operation: how to create an environment variable that contains executable command results. 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 ". In this example, we need to point out several points. In the first line, the command to be executed is enclosed in reverse quotation marks. It is not a standard single quotation mark, but a single quotation mark usually located above the Tab key on the keyboard. You can use the bash alternative 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 multiple methods to perform exactly the same operation. With command replacement, you can place any command or command pipeline between ''or $ () and assign it to environment variables. Really convenient! The following is an example to demonstrate how to use pipelines in command replacement:
MYFILES = $ (ls/etc | grep pa)
Bash-2.03 $ echo $ MYFILES
Pam. d passwd
Truncates a string like a professional
Although basename and dirname are good tools, you may sometimes need to perform more advanced string "truncation", not just standard path name operations. You can use the built-in variable extension function of bash to make it more convincing. Variable extensions of the standard type similar to $ {MYVAR} have been used. However, bash itself can also execute some convenient string truncation. Take a look at these

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.