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
- VaR= "Hello"
- VaR= Hello
- 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
- VaR= "Hello World"
var="Hello World"
In this case, quotation marks are required.
3.
JS Code
- 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
- Echo $VaR
echo $var
This is why strings in shell do not need to be enclosed in quotation marks. If you run
JS Code
- 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
- VaR= World
- Var2 = "$ var world"
- 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
- VaR= World
- Var2 = '$ var world'
- 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
- If[Condition]
- Then
- Action
- Elif [condition2]
- Then
- Action2
- .
- .
- .
- Elif [condition3]
- Then
- Else
- Actionx
- 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
- VaR= "One two three four"
- ForXIn$VaR
- Do
- Echo $ x
- 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
- While[Condition]
- Do
- Statements
- Done
while [ condition ] do statements done
JS Code
- Until [condition]
- Do
- Statements
- 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
- Gender = "boy"
- If["$ Gender" = "girl"]
- Then
- Echo 'Welcome! '
- Else
- Echo 'we only welcome girl .'
- 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
- Arithmetic comparison operator
- Num1-eq num2 equals to [3-EQ $ mynum]
- Num1-ne num2 is not equal to [3-ne $ mynum]
- Num1-lt num2 less than [3-lt $ mynum]
- The num1-le num2 is less than or equal to [3-Le $ mynum]
- Num1-gt num2 greater than [3-GT $ mynum]
- 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
- 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, 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"]
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
- Gender = "boy"
- Case"$ Gender"In
- Boy)
- Echo "We only welcome girl ."
- ;;
- Girl)
- Echo 'Welcome! '
- ;;
- *)
- Echo "unknow ."
- ;;
- 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
- 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
- Echo $(1 + 1 ))
echo $((1+1))
Iv. Functions
JS Code
- Add (){
- Result = 0
- ForNIn$ *
- Do
- Result = $ ($ result + $ n ))
- Done
- Return$ Result
- }
add(){ result=0 for n in $* do result=$(($result+$n)) done return $result}
Run:
Java code
- Add 1 2 3
- Echo $?
- 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
- 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, true [/tmp/install/etc/services-nt/etc/services]
- 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
- ForFileIn/Home /*
- Do
- If[-D "$ file"]
- Then
- Echo $ file is a directory
- Fi
- 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
- ForUserIn'Awk-F ":" '{print $1}'/etc/passwd'
- Do
- Echo find user $ user
- 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