Shell (BASH) Study Notes

Source: Internet
Author: User
Tags case statement syslog

I used to read some articles and learn more about them. I usually write a simple command combination, but I have never written complex scripts. Recently, I wrote a script to restore the data and found that the optical field does not work properly. By the way, take study notes.

Convention: the shell in this Article refers to bash.

Because the javaeye blog editor does not provide the shell code format, You have to insert the code in Javascript script format.

I. Variables

Directly assign values to variables without prior declaration.

JS Code
  1. VaR= "Hello"
  2. VaR= Hello
  3. VaR= 'Hello'
var="Hello"var=Hellovar='Hello'

 

Notes:

1. There must be no space between variables and values. Otherwise, the interpreter may consider the variables and values as several commands. Many programmers prefer to leave spaces on both sides of the = sign for good looks, but this does not work in shell.

2. strings do not need to use "signs or". The above assignment methods are equivalent. Unless there is a space between strings.

For example:

JS Code
  1. VaR= "Hello World"
var="Hello World"

 

In this case, quotation marks are required.

3.

JS Code
  1. VaR=
var=

This statement is also valid, indicating that the value of VaR is null.

 

4. When using a variable, you need to add the $ symbol before the variable. PHP programmers are familiar with this.

For example:

JS Code
  1. Echo $VaR
echo $var

 

This is why strings in shell do not need to be enclosed in quotation marks. If you run

JS Code
  1. EchoVaR
echo var

 

The system treats VaR as a string rather than a variable. Another advantage of adding the $ sign before the variable is to use the variable directly in the string when outputting the variable in the string.

For example:

JS Code

  1. VaR= World
  2. Var2 = "$ var world"
  3. Echo $ var2
var=Worldvar2="$var World"echo $var2

 

 

However, unlike PHP, you do not need to add the $ symbol when assigning values to variables. Because the shell does not contain the = symbol, the = symbol is used to judge equality. If $ is added when the value is assigned, confusion will occur.

Note that the variables in the single quotes (') string will not be replaced.

 

JS Code
  1. VaR= World
  2. Var2 = '$ var world'
  3. Echo $ var2
var=Worldvar2='$var World'echo $var2

Output result of the preceding statement: $ var world

This can be used to output special symbols such as $, without worrying about the replacement of characters as variables.

Ii. Statements

1. The shell statement does not need to be used; the number ends unless several statements are written in the same line.

2. The statement block in the shell does not need to be expanded by the {} sign. If statements generally end with Fi. Of course, this is also a special case, which will be mentioned later.

3. If statement

JS Code
  1. If[Condition]
  2. Then
  3. Action
  4. Elif [condition2]
  5. Then
  6. Action2
  7. .
  8. .
  9. .
  10. Elif [condition3]
  11. Then
  12. Else
  13. Actionx
  14. Fi
if [ condition ]then     actionelif [ condition2 ]then     action2...elif [ condition3 ]then else    actionxfi

It should be noted that there is no elseif in shell, but Elif (this abbreviation is too abnormal, is it necessary ?).

Each or Elif is followed by then, and must be wrapped or used; separated. Then can be in a row with the subsequent action.

 

3. For Loop

JS Code
  1. VaR= "One two three four"
  2. ForXIn$VaR
  3. Do
  4. Echo $ x
  5. Done
var="one two three four"for x in $vardo     echo $xdone

The for loop starts to end with do and done. do not end with ROF.

4. While and util Loops

 

JS Code
  1. While[Condition]
  2.  Do
  3. Statements
  4. Done
while [ condition ] do     statements done

 

JS Code
  1. Until [condition]
  2.  Do
  3. Statements
  4. Done
until [ condition ] do     statements done

 

 

 

5. conditional statements

The condition statements in shell are enclosed by [] and used in if, while, until, and other structures.

For condition determination, use = rather than =. The Condition Statement and [] must be separated by spaces.

For example:

 

JS Code
  1. Gender = "boy"
  2. If["$ Gender" = "girl"]
  3. Then
  4. Echo 'Welcome! '
  5. Else
  6. Echo 'we only welcome girl .'
  7. Fi
gender="boy"if [ "$gender" = "girl" ]then      echo 'Welcome!'else      echo 'We only welcome girl.'fi

Note that the = clause must be separated by spaces. Otherwise, shell processes the condition statement as a string and the condition is always true. It is best to use the "sign" in the Condition Statement. Otherwise, if the variable contains spaces, shell will report the too arguments error. If the variable is empty, the =: unary operator expected. error is returned. If the variable is null, The Condition Statement is missing one side. Of course, an error occurs. So,Returns the stringEnclose variables in double quotes is a good habit of shell programming, especially in conditional statements.

 

Other comparison symbols, such as >,<, cannot be used directly in the condition statement, because> has special meanings in shell. The following is a shell comparison operator number representation method:

 

XML Code
  1. Arithmetic comparison operator
  2. Num1-eq num2 equals to [3-EQ $ mynum]
  3. Num1-ne num2 is not equal to [3-ne $ mynum]
  4. Num1-lt num2 less than [3-lt $ mynum]
  5. The num1-le num2 is less than or equal to [3-Le $ mynum]
  6. Num1-gt num2 greater than [3-GT $ mynum]
  7. Num1-ge num2 is greater than or equal to [3-ge $ mynum]
Arithmetic comparison operator num1-eq num2 equals [3-EQ $ mynum] num1-ne num2 not equal to [3-ne $ mynum] num1-lt num2 less than [3-lt $ mynum] num1-le num2 less than or equal [3-Le $ mynum] The num1-gt num2 is greater than [3-GT $ mynum] The num1-ge num2 is greater than or equal to [3-ge $ mynum]

 

XML Code
  1. String comparison operator
  2. -Z string if the string length is zero, it is true [-z "$ myvar"]
  3. -N string if the string length is not zero, it is true [-n "$ myvar"]
  4. String1 = string2 if string1 is the same as string2, it is true ["$ myvar" = "One Two Three"]
  5. String1! = String2 if string1 is different from string2, it is true ["$ myvar "! = "One Two Three"]
String comparison operator-Z string if the string length is zero, it is true [-z "$ myvar"]-N string if the string length is not zero, true [-n "$ myvar"] string1 = string2 if string1 and string2 are the same, true ["$ myvar" = "One Two Three"] string1! = String2 if string1 is different from string2, it is true ["$ myvar "! = "One Two Three"]

6. Case statement

 

JS Code
  1. Gender = "boy"
  2. Case"$ Gender"In
  3. Boy)
  4. Echo "We only welcome girl ."
  5. ;;
  6. Girl)
  7. Echo 'Welcome! '
  8. ;;
  9. *)
  10. Echo "unknow ."
  11. ;;
  12. Esac
gender="boy" case "$gender" in      boy)            echo "We only welcome girl."            ;;      girl)            echo 'Welcome !'            ;;      *)            echo "unknow."            ;; esac  

The syntax of the case statement is strange. At first glance, it is awkward. Each pattern is enclosed in semi-brackets and ended.

Iii. Arithmetic

Shell is used to process strings by default, So if you directly run:

JS Code
  1. Echo 1 + 1
echo 1+1

It will directly output 1 + 1 instead of 2. To calculate the value of an expression, you only need to use "$ (" and ")" to enclose the expression.

JS Code
  1. Echo $(1 + 1 ))
echo $((1+1))

 

Iv. Functions

JS Code
  1. Add (){
  2. Result = 0
  3. ForNIn$ *
  4. Do
  5. Result = $ ($ result + $ n ))
  6. Done
  7. Return$ Result
  8. }
add(){    result=0    for n in $*    do        result=$(($result+$n))    done    return $result}

Run:

 

Java code
  1. Add 1 2 3
  2. Echo $?
  3. Echo $ result
add 1 2 3echo $?echo $result

Both outputs are: 6.

Here are some notes: in shell, the return value of the function cannot be directly obtained. If you want to use the function return value, you can only use global variables for transmission. The variables in shell are global by default, unless you have added the local modifier before. In the preceding example, The result variable is also visible outside the function. If you add the local modifier before the result, the result variable is invisible outside the function. But shell places the function return value in $? In global variables, you can use $? To obtain the return value of the previous function call. $ * All input parameters of the function can be obtained. $1 indicates the first parameter, and so on.

 

V. Miscellaneous

Some built-in features of shell can easily process files and interact with other programs.

XML Code
  1. File comparison operator
  2. -E filename if filename exists, it is true [-E/var/log/syslog]
  3. -D filename if filename is a directory, it is true [-D/tmp/mydir]
  4. -F filename if filename is a regular file, it is true [-F/usr/bin/grep]
  5. -L filename if filename is a symbolic link, it is true [-L/usr/bin/grep]
  6. -R filename if filename is readable, it is true [-r/var/log/syslog]
  7. -W filename if filename is writable, it is true [-W/var/mytmp.txt]
  8. -X filename if filename is executable, it is true [-L/usr/bin/grep]
  9. Filename1-nt filename2 if filename1 is newer than filename2, true [/tmp/install/etc/services-nt/etc/services]
  10. Filename1-ot filename2 if filename1 is older than filename2, true [/boot/bzimage-ot ARCH/i386/boot/bzimage]
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, true [-L/usr/bin/grep]-r filename if filename is readable, true [-r/var/log/syslog]-W filename if filename is writable, true [-W/var/mytmp.txt]-x filename if filename is executable, true [-L/usr/bin/grep] filename1-nt filename2 if filename1 is newer than filename2, true [/tmp/install/etc/services-nt/etc/services] filename1-ot filename2 if filename1 is older than filename2, it is true [/boot/bzimage-ot ARCH/i386/boot/bzimage]

 

It is easy to traverse files in a for loop.

JS Code
  1. ForFileIn/Home /*
  2. Do
  3. If[-D "$ file"]
  4. Then
  5. Echo $ file is a directory
  6. Fi
  7. Done
for file in /home/*do   if [ -d "$file" ]    then      echo $file is a directory    fidone

It is easy to call the output results of other programs:

 

JS Code
  1. ForUserIn'Awk-F ":" '{print $1}'/etc/passwd'
  2. Do
  3. Echo find user $ user
  4. Done
for user in `awk -F":" '{ print $1 }' /etc/passwd`do    echo find user $userdone

To use the output results of other commands in shell footsteps, you only need to use the 'symbol to include the commands. Note: This symbol is not a single quotation mark. It is in the upper-left corner of the keyboard.

 

6. Postscript

The basic shell syntax has learned this, and the advanced syntax has not been implemented yet. This note is almost long, and you can learn and write it again. Shell is the foundation. Only tools such as awk, grep, and sed can work out the results. I recently talked about several basic philosophical principles of * nix in Unix programming art. One of these principles is:

Combination Principle: Consider splicing and combination during design

* The input and output of Nix system programs are generally simple, streamlined, and stream-oriented. This facilitates interaction and Splicing between programs. * Programs in the nix system generally only complete a single function. If you need a complex function, you need to splice the applet together. This feature also determines the importance of shell in the * uix system.

 

7. Shell learning materials

1. IBM shell programming Series

Many examples and materials in this article are from this series of tutorials.

2. Bash Reference Manual

GNU bash official reference manual

 

Related Article

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.