Bash instance (2)

Source: Internet
Author: User
Article title: Bash instance (2 ). 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.
In the previous bash introductory article, Daniel Robbins explained some basic elements of the script language and the reasons for using bash. In this article (the second part), Daniel continues with the content of the previous article and explains the condition (if-then) statements, loops, and more basic bash structures.
Let's take a look at the simple technique for processing command line independent variables, and then look at the basic programming structure of bash.
Receive independent variable
In the sample program in the introductory article, we use the environment variable "$1" to reference the first command line independent variable. Similarly, you can use "$2" and "$3" to reference the second and third independent variables passed to the script. Here is an example:
#! /Usr/bin/env bash
Echo name of script is $0
Echo first argument is $1
Echo second argument is $2
Echo seventeenth argument is $17
Echo number of arguments is $ #
In addition to the following two details, this example is not required. First, "$0" is extended to the script name called from the command line, and "$ #" is extended to the number of independent variables passed to the script. Test the above script and learn how it works by passing different types of command line independent variables.
It is sometimes necessary to reference all command line arguments at a time. For this purpose, bash implements the variable "$ @", which is extended to all command line parameters separated by spaces. In the "for" loop later in this article, you will see an example of using this variable.
Bash programming structure
If you have used programming in a procedural language like C, Pascal, Python, or Perl, you must be familiar with the standard programming structure like the "if" statement and "for" loop. Bash has its own version for most of these standard structures. In the following sections, we will introduce several bash structures and demonstrate the differences between these structures and those in other programming languages that you are already familiar. Don't worry if you haven't programmed much before. I provide enough information and examples to keep up with the progress of this article.
Convenient condition statements
If you have used C to write file-related code, you should know: to compare a specific file, whether it is more work than another file. That's because C does not have any built-in syntax for this comparison. two stat () calls and two stat structures must be used for manual comparison. Instead, bash has built-in standard file comparison operators. Therefore, it is as easy to determine whether "/tmp/myfile is readable" as to check whether "$ myvar is greater than 4.
The following table lists the most common bash comparison operators. Examples of how to correctly use each option are also provided. The example must be followed by "if. For example:
If [-z "$ myvar"]
Then
Echo "myvar is not defined"
Fi
Operator Description Example
File comparison operator
-E filename if filename exists, it is true [-e/var/log/syslog]
-D filename if filename is a directory, it is true [-d/tmp/mydir]
-F filename if filename is a regular file, it is true [-f/usr/bin/grep]
-L filename if filename is a symbolic link, it is true [-L/usr/bin/grep]
-R filename if filename is readable, it is true [-r/var/log/syslog]
-W filename if filename is writable, it is true [-w/var/mytmp.txt]
-X filename if filename is executable, it is true [-L/usr/bin/grep]
Filename1-nt filename2 if filename1 is newer than filename2, it is true [/tmp/install/etc/services-nt/etc/services]
Filename1-ot filename2 if filename1 is earlier than filename2, true [/boot/bzImage-ot arch/i386/boot/bzImage]
String comparison operator (please note the use of quotation marks, which is a good way to prevent space from disturbing the code)
-Z string if the string length is zero, it is true [-z "$ myvar"]
-N string if the string length is not zero, it is true [-n "$ myvar"]
String1 = string2 if string1 is the same as string2, it is true ["$ myvar" = "one two three"]
String1! = String2 if string1 is different from string2, it is true ["$ myvar "! = "One two three"]
Arithmetic comparison operator
Num1-eq num2 equals to [3-eq $ mynum]
Num1-ne num2 is not equal to [3-ne $ mynum]
Num1-lt num2 is less than [3-lt $ mynum]
Num1-le num2 is less than or equal to [3-le $ mynum]
Num1-gt num2 is greater than [3-gt $ mynum]
Num1-ge num2 is greater than or equal to [3-ge $ mynum]
Sometimes there are several different methods for specific comparison. For example, the following two code segments have the same functions:
If ["$ myvar"-eq 3]
Then
Echo "myvar equals 3"
Fi
If ["$ myvar" = "3"]
Then
Echo "myvar equals 3"
Fi
The above two comparisons perform the same function, but the first uses arithmetic comparison operators, and the second uses string comparison operators.
String comparison
Most of the time, although double quotation marks that enclose strings and string variables are not used, this is not a good idea. Why? If the environment variable happens to have a space or tabulation key, bash will not be able to distinguish and thus it will not work properly. Here is an error comparison example:
If [$ myvar = "foo bar oni"]
Then
Echo "yes"
Fi
In the above example, if myvar is equal to "foo", the code will work as expected without printing. However, if myvar is equal to "foo bar oni", The Code fails due to the following error:
[: Too required arguments
In this case, spaces in "$ myvar" (equal to "foo bar oni") confuse bash. After bash expands "$ myvar", the code is as follows:
[Foo bar oni = "foo bar oni"]
Bash considers that there are too many independent variables in square brackets because the environment variables are not placed in double quotes. Double quotation marks can be used to enclose string independent variables to eliminate this problem. Keep in mind that many similar programming errors will be removed if all string independent variables are enclosed in double quotation marks. The comparison of "foo bar oni" should be written:
If ["$ myvar" = "foo bar oni"]
Then
Echo "yes"
Fi
More references
To expand environment variables, you must enclose them in double quotation marks instead of single quotation marks. Variable (and history) extensions are disabled in single quotes.
The above code will work as expected without any unpleasant surprises.
Loop structure: ""
Well, we have already talked about conditional statements. next we should explore the bash loop structure. We will start with the standard "for" loop. Here is a simple example:
#! /Usr/bin/env bash
For x in one two three four
Do
Echo number $ x
Done
Output:
Number one
Number two
Number three
Number four
What happened? The "for x" section in the "for" loop defines a new environment variable named "$ x" (also called a loop control variable ), its values are set to "one", "two", "three", and "four" in sequence ". After each assignment, run the code between "do" and "done ). In a loop, like other environment variables, use the standard variable extension syntax to reference the loop control variable "$ x ". Note that the "for" loop always receives a certain type of word list after the "in" statement. In this example, four English words are specified, but the word list can also reference files on the disk, or even file wildcards. Take a look at the following example to demonstrate how to use the standard shell wildcard:
#! /Usr/bin/env bash
For myfile in/etc/r *
Do
If [-d "$ myfile"]
Then
Echo "$ myfile (dir )"
Else
Echo "$ myfile"
Fi
Done
Output:
/Etc/rc. d (dir)
/Etc/resolv. conf
/Etc/resolv. conf ~
/Etc/rpc
The code above lists each file starting with "r" in/etc. To do this, bash first obtains the wildcard/etc/r * before executing the loop, then extends it, and uses the string/etc/rc. d/etc/resolv. conf/etc/resolv. conf ~ /Etc/rpc replacement. Once a loop is entered, the "-d" condition operator is used to perform two different operations based on whether the myfile is a directory. If it is a directory, "(dir)" is appended to the output line.
You can also use multiple wildcards or even environment variables in the word list:
For x in/etc/r ??? /Var/lo */home/drobbins/mystuff/*/tmp/$ {MYPATH }/*
Do
Cp $ x/mnt/mydir
Done
Bash will execute wildcards and environment variable extensions in all correct locations, and may create a very long word list.
Although all wildcard extension examples use absolute paths, you can also use relative paths, as shown below:
For x in ../* mystuff /*
Do
Echo $ x is a silly file
Done
In the above example, bash executes wildcard extension relative to the current working directory, just like using relative paths in the command line. Study wildcard extension. You will notice that if an absolute path is used in the wildcard, bash expands the wildcard into an absolute path list. Otherwise, bash uses the relative path in the word list. If you only reference files in the current working directory (for example, if you enter "for x in *"), the generated file list will have no prefix for path information. Remember, you can use the "basename" executable program to remove the preceding path information, as shown below:
For x in/var/log /*
Do
Echo 'basename $ X' is a file living in/var/log
Done
Of course, it is usually convenient to execute a loop on the command line independent variables of the script. Here is an example of how to use the variable "$ @" mentioned at the beginning of this article:
#! /Usr/bin/env bash
For thing in "$ @"
Do
Echo you typed $ {thing }.
Done
Output:
$ Allargs hello there you silly
You typed hello.
You typed there.
You typed you.
You typed silly.
Shell arithmetic
Before learning another type of loop structure, you 'd better familiarize yourself with how to execute shell arithmetic. Yes, indeed: you can use the shell structure to perform simple integer operations. Bash only needs to enclose a specific arithmetic expression with "$ (" and ")" to calculate the expression. Here are some examples:
$ Echo $ (1, 100/3 ))
33
$ Myvar = "56"
$ Echo $ ($ myvar + 12 ))
68
$ Echo $ ($ myvar-$ myvar ))
0 $ myvar =$ ($ myvar + 1 ))
$ Echo $ myvar
57
You are familiar with how to perform mathematical operations.

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.