1. "Type" detection of a file name (presence or absence), such as TEST-E filename
-E Does the "file name" exist? Common
-F is the "file name" an archive (file)? Common
-D is the "file name" directory? Common
-B is the "file name" a block device device?
-C is the "file name" a character device?
-S is the "file name" a Socket file?
-P is the "file name" a FIFO (pipe) file?
-L is the "file name" a link file?
2. Permission detection for files, such as Test-r filename
-R to detect if the file name has a "readable" attribute?
-W to detect if the file name has a "writable" attribute?
-X detects if the file name has an "executable" attribute?
-U detects if the file name has a "SUID" attribute?
-G to detect if the file name has a "SGID" attribute?
-K detects if the file name has a "Sticky bit" attribute?
-S detects if the file name is a "non-blank file"?
3. Comparisons between two files, such as: Test file1-nt file2
-nt (newer than) to determine whether File1 is newer than file2
-ot (older than) to determine whether File1 is older than file2
-ef Judge File2 and File2 is the same file, can be used in judging hard link judgment. The main significance in determining whether two files are all pointing to the same inode!
4. About a decision between two integers, such as test n1-eq N2
-eq two values equal (equal)
-ne two values unequal (not equal)
-GT N1 greater than N2 (greater than)
-LT N1 smaller than N2 (less than)
-ge n1 greater than or equal to N2 (greater than or equal)
-le N1 less than or equal to N2 (lesser than or equal)
5. Determining the data of a string
Test-z string to determine whether the strings are 0? True if string is an empty string
Test-n string to determine whether strings are not 0? False if string is an empty string.
Note:-n can also be omitted
Test STR1 = STR2 Determines whether the str1 equals str2, and if equal, the callback True
Test STR1! = STR2 Determines if the str1 is not equal to str2, and if equal, the callback false
6. Multiple criteria determination, for example: Test-r filename-a-x filename
-A (and) two conditions at the same time set up! For example Test-r file-a-x file, the file will return true if it has both R and X permissions.
-O (or) two conditions any one set up! For example Test-r file-o-x file, the file can return true if it has R or X permissions.
! Inverting state, such as test! -x file, which callbacks true when file does not have X
5. Shell Script Syntax previous page 31st Shell script next page
--------------------------------------------------------------------------------
5. Shell Scripting Syntax please review 5.1. Condition testing: Test [Please review
The command test or [can test whether a condition is true, if the test result is real, the exit status of the command is 0, if the test result is false, the exit status of the command is 1 (note the exact opposite of the logical representation of the C language). For example, test the size relationship of two numbers:
$ var=2$ Test $VAR-gt 1$ echo $?0$ test $VAR-gt 3$ echo $?1$ [$VAR-gt 3]$ Echo $?1
Although it may seem strange, the left parenthesis [is really a command name, the arguments to the command should be separated by a space, for example, $VAR,-GT, 3,] are [four parameters of the command, they must be separated by a space. The command test or [Parameter form is the same, except that the test command does not require] parameters. For the [command] example, the common test commands are shown in the following table:
Table 31.2. Test command
[-D dir] true if Dir exists and is a directory [-f file] True if file exists and is a normal file [-Z string] True if the length of string is zero [-n string] True if the length of string is nonzero [strin G1 = STRING2] If two strings are the same then true [STRING1! = STRING2] If the strings are different then true [ARG1 OP ARG2]arg1 and ARG2 should be integers or variables with integer values, OP is-eq (equals)-ne (not equal to)-lt (less than)-le (less than or equal)-GT (greater than)-ge (greater than or equal) one of the
Similar to the C language, test conditions can also be done with, or, non-logical operations:
Table 31.3. Test commands with and, or, not
[ ! EXPR]expr can be any of the test conditions in the table above! Represents the logical inverse of [expr1-a EXPR2]expr1 and EXPR2 can be any of the test conditions in the table above,-a representation of logic with [Expr1-o EXPR2] EXPR1 and EXPR2 can be any of the test conditions in the table above, and-o represents a logical OR
For example:
$ var=abc$ [-D desktop-a $VAR = ' abc ']$ echo $?0
Note that if the $var variable in the previous example is not defined beforehand, the shell is expanded to an empty string, resulting in a syntax error for the test condition (expanded to [-D desktop-a = ' abc '), and as a good shell programming habit, the variable value should always be placed in double quotes (expanded to [-D desktop-a "" = ' abc ']):
$ unset var$ [-d desktop-a $VAR = ' abc ']bash: [: Too many arguments$ [-D desktop-a ' $VAR ' = ' abc ']$ echo $?15.2. if/ THEN/ELIF/ELSE/FI Please review
Similar to the C language, in the shell with the IF, then, elif, else, fi these commands to achieve branch control. This process Control statement is essentially made up of several shell commands, such as the one previously said
If [-f ~/.BASHRC]; Then. ~/.bashrcfi
is actually three commands, if [-F ~/.BASHRC] is the first, then. ~/.BASHRC is the second, FI is the third article. If the two commands are written in the same line, they need to be separated from each other, and a single command on one line does not need to be written; number, and then there is a newline after that, but this command is not finished, the shell will automatically continue, the next line after then as a command processing. As with the command, be aware that the command and parameters must be separated by a space. If the parameter of the IF command consists of a sub-command, if the subcommand's exit status is 0 (true), then the subcommands that follow then are executed, and if exit status is not 0 (false), then the subcommands after elif, else, or fi are executed. A subcommand after an if is usually a test command, but it can also be another command. The shell script does not have {} brackets, so use fi to indicate the end of the IF statement block. See the following example:
#! /bin/shif [-f/bin/bash]then echo "/bin/bash is a file" else echo "/bin/bash was not a file" FIIF:; Then echo "Always true"; Fi
: is a special command called the Empty command, which does nothing, but exit status is always true. In addition, you can also perform/bin/true or/bin/false to get a true or false exit Status. Let's look at an example:
#! /bin/shecho "Is it morning? Please answer yes or No. " Read Yes_or_noif ["$YES _or_no" = "YES"]; Then echo "Good morning!" elif ["$YES _or_no" = "NO"]; Then echo "Good afternoon!" else echo "Sorry, $YES _or_no not recognized. Enter yes or No. "Exit 1fiexit 0
The read command in the previous example is to wait for the user to enter a line of string to store the string in a shell variable.
In addition, the shell also provides && | | syntax, similar to the C language, has short-circuit features, and many shell scripts like to write this:
Test "$ (whoami)"! = ' root ' && (echo you is using a non-privileged account; Exit 1)
&& equivalent to "If...then ..." while | | Equivalent to "if Not...then ...". && | | Used to connect two commands, while the-A and-o above are used only to connect two test conditions in a test expression, be aware of their differences, for example,
Test "$VAR"-gt 1-a "$VAR"-LT 3
is equivalent to the following notation
Test "$VAR"-GT 1 && Test "$VAR"-lt 35.3. CASE/ESAC Please review
The case command is analogous to the C-switch/case statement, and ESAC represents the end of the case statement block. The case of a C language can only match integer or character constant expressions, whereas shell script case matches strings and wildcard, each matching branch can have several commands, which must be at the end; At the end, when execution finds the first matching branch and executes the corresponding command, and then jumps directly to ESAC, you do not need to jump out of the same language as C.
#! /bin/shecho "Is it morning? Please answer yes or No. " Read Yes_or_nocase "$YES _or_no" inyes|y| yes| YES) echo "Good morning!";; [nn]*] echo "good afternoon!";; *) echo "Sorry, $YES _or_no not recognized. Enter yes or No. "Exit 1;; Esacexit 0
Examples of using case statements can be found in the script directory/ETC/INIT.D of the system services. Most of the scripts in this directory have this form (take/etc/apache2 as an example):
Case $ in start) ...;; stop) ...;; Reload | Force-reload) ...;; Restart) log_success_msg "Usage:/etc/init.d/apache2 {start|stop|restart|reload|force-reload| Start-htcacheclean|stop-htcacheclean} "exit 1;; Esac
The command to start the Apache2 service is
$ sudo/etc/init.d/apache2 Start
$ $ is a special variable that is automatically evaluated as the first command-line argument when executing the script, that is, start, so enter the start branch to execute the related command. Similarly, command-line arguments are specified as stop, reload, or restart to enter other branches to perform the command to stop the service, reload the configuration file, or restart the service.
5.4. For/do/done Please review
The For loop structure of a shell script is very different from the C language, and it resembles a foreach loop for some programming languages. For example:
#! /bin/shfor FRUIT in apple banana pear; Do echo ' I like $FRUIT ' done
Fruit is a loop variable, the first loop $fruit is Apple, the second value is banana, the third value is pear. For example, to change the current directory of Chap0, CHAP1, CHAP2 and other file names to chap0~, chap1~, chap2~, etc. (by convention, at the end of the ~ character filename represents a temporary file), this command can write:
$ for FILENAME in chap?; Do MV $FILENAME $FILENAME ~; Done
You can also write this:
$ for FILENAME in ' ls chap? '; Do MV $FILENAME $FILENAME ~; done5.5. While/do/done Please review
The use of while is similar to the C language. For example, a script that validates a password:
#! /bin/shecho "Enter password:" Read trywhile ["$TRY"! = "secret"]; Do echo "Sorry, try again" read Trydone
The following example controls the number of loops by arithmetic operations:
#! /bin/shcounter=1while ["$COUNTER"-lt 10]; Do echo ' Here we go Again ' counter=$ (($COUNTER + 1)) done
The shell also has a until loop, similar to the C-language do...while loop. This chapter withheld.
Exercise Please review
1, the above verification password program modification, if the user five times the wrong password error exit.
5.6. Position parameters and special variables please review
There are a number of special variables that are automatically assigned by the shell, and we have already encountered $? and $ $, and now summarize:
Table 31.4. Common positional parameters and special variables
$ A is equivalent to the C language main function of argv[0]$1, $ ... these are called positional parameters (positional Parameter), equivalent to the C language main function argv[1], argv[2]...$ #相当于C语言main函数的argc -1, note that the following # does not indicate a comment [email protected] represents the parameter list "$" "$" ..., for example, can be used in the for loop in the back. $? Exit of the previous command status$$ the current shell's process number
The position parameter can be shifted left with the shift command. For example, shift 3 means that the original $4 now become $ $, the original $ $ now becomes $ $, and so on, the original $, $, $ discard, $ not move. The shift command with no parameters is equivalent to shift 1. For example:
#! /bin/shecho "The program $ is now running" echo "the first parameter was" echo "the second parameter is" echo "the Para Meter list is [e-mail protected] "Shiftecho" The first parameter is $ "echo" the second parameter is "echo" the parameter list is [email protected] "5.7. function Please review
Similar to the C language, there is also the concept of a function in the shell, but there is no return value in the function definition and no argument list. For example:
#! /bin/shfoo () {echo "Function foo is called";} echo "-=start=-" Fooecho "-=end=-"
Note that the left curly brace {and subsequent commands of the function body must have spaces or line breaks, and if the last command and the closing curly brace} are written on the same line, the end of the command must have;
When you define the Foo () function, you do not execute the command in the function body, just as you would define a variable, only a definition of the name foo, and then execute the command in the function body when you call the Foo function (note that the function calls in the shell do not write parentheses). A function in a shell script must be defined and called before the function definition is written in front of the script, and the function call and other commands are written at the end of the script (similar to the C language's main function, which is where the entire script actually starts executing the command).
The shell function does not have a parameter list does not mean that can not pass parameters, in fact, the function is like a mini script, call the function can be passed arbitrary parameters, in the function is also used by the variables such as $, $, $ to extract the parameters, the function of positional parameters equivalent to the local variables of the function, Changing these variables does not affect variables such as $, $, $, and so on outside the function. The function can be returned with the return command, if the return followed by a number represents the exit Status of the function.
The following script can be used to create multiple directories at once, each directory name passed through the command line parameters, the script tests the existence of each directory, and if the directory does not exist, first print the information and then try to create the directory.
#! /bin/shis_directory () {dir_name=$1 if [!-D $DIR _name]; then return 1 else return 0 fi}for DIR in "[email protected]"; Do if Is_directory "$DIR" then:else echo "$DIR doesn ' t exist. Creating it now ... "mkdir $DIR >/dev/null 2>&1 if [$?-ne 0]; Then echo "Cannot create directory $DIR" Exit 1 fi fidone
Note that is_directory () returns 0 for true return 1 for false.
This article is from the "Lazy" blog, please be sure to keep this source http://5675012.blog.51cto.com/5665012/1600967
If and related judgments in the shell