Basic shell script syntax

Source: Internet
Author: User

I. Basic Shell syntax

1. Variables
By convention, Shell variables are composed of uppercase letters and underscores (_). There are two types of Shell variables:

Environment Variable
Environment variables can be transmitted from the parent process to the child process. Therefore, the environment variables of the Shell process can be transmitted from the current Shell process to the child process fork. Use the printenv command to display the environment variables of the Current Shell Process.
Local variable
It only exists in the current Shell process. You can use the set command to display all variables (including local variables and environment variables) and functions defined in the current Shell process. Environment variables are a concept inherent in any process, while local variables are unique to Shell. In Shell, the definitions and usage of environment variables and local variables are similar. Define or assign a variable in Shell:
$ VARNAME = value
Note that no space is allowed on both sides of the equal sign. Otherwise, Shell will interpret the equal sign as a command or a command line parameter.
A variable is defined only in the current Shell process. It is a local variable. You can use the export command to export local variables as environment variables. You can define and export environment variables in one step:
$ Export VARNAME = valueYou can also do this in two steps:
$ VARNAME = value $ export VARNAMEYou can use the unset command to delete defined environment variables or local variables.
$ Unset VARNAMEIf a variable is named VARNAME, $ {VARNAME} can be used to represent its value, and $ VARNAME can be used to represent its value without ambiguity. The following example compares the differences between the two representations:
$ Echo $ SHELL $ echo $ SHELLabc $ echo $ SHELL abc $ echo $ {SHELL} abcNote: $ is not required when defining a variable. $ is used when getting the variable value. Different from the C language, Shell variables do not need to clearly define the type. In fact, the Shell variable value is a string. For example, we define VAR = 45. In fact, the VAR value is a string 45 rather than an integer. Shell variables do not need to be defined first and then used. If no value is defined for a variable, the value is a null string.

2. Globbing ):*? []
These matching characters are called wildcards (Wildcard), as shown below:

2. 1. wildcard
*
Matches 0 or multiple arbitrary characters
?
Match any character
[Several characters]
Occurrence of any character in square brackets

$ Ls/dev/ttyS * $ ls ch0 ?. Doc $ ls ch0[0-22.16.doc $ ls ch%012%%0-92.16.docThe parameters passed to the ls command are actually the two file names, rather than a matching string.

3. Command replacement: 'or $ ()
It is also a command enclosed by backquotes. Shell executes the command first and then immediately replaces the output result with the current command line. For example, define a variable to store the output of the date command:
$ DATE = 'date' $ echo $ dateThe command replacement can also be represented by $:
$ DATE = $ (date)
4. Arithmetic substitution: $ (())
Used for arithmetic calculation. The Shell variable value in $ () is converted to an integer. For example:
$ VAR = 45 $ echo $ ($ VAR + 3 ))$ () Can only use the +-*/and () operators, and can only perform integer operations.

5. Escape Character \
Similar to the C language, \ is used as an escape character in Shell to remove the special meaning of a single character that follows it (except for carriage return). In other words, the character that follows it takes the literal value. For example:
$ Echo $ SHELL/bin/bash $ echo \ $ SHELL $ echo \\\For example, you can create a file named "$" as follows:
$ Touch \ $ \\$Although a character does not have a special meaning, it is also very troublesome to use it as a file name, that is, the-number. If you want to create a file whose name starts with "-", this will not work:
$ Touch-hellotouch: invalid option -- hTry 'touch -- help' for more information.Even if \ escape is added, an error is returned:
$ Touch \-hellotouch: invalid option -- hTry 'touch -- help' for more information.All UNIX commands use the command line parameters starting with "-" as Command Options, rather than file names. To process a file name starting with "-", you can use either of the following methods:
$ Touch./-helloOr
$ Touch ---hello\ Another method is to press \ and then press enter to continue the line. Shell does not immediately execute the command, but moves the cursor to the next line and provides a prompt>, wait for the user to continue the input, and finally run all the continued rows together as a command. For example:
$ Ls \>-l (ls-l command output)
6. Single quotes
Unlike the C language, single quotation marks and double quotation marks in Shell scripts are the same as string delimiters (next section of double quotation marks), rather than character delimiters. Single quotation marks are used to keep the nominal values of all characters in the quotation marks. Even if the \ and carriage return characters in the quotation marks are no exception, the single quotation marks cannot appear in the string. If the quotation marks are not paired, enter the carriage return. Shell will give a prompt to continue the line, asking the user to enclose the quotation marks with a pair. For example:
$ Echo '$ shell' $ SHELL $ echo 'abc \ (Press ENTER)> de' (Press enter again to end the command) ABC \ DE
7. Double quotation marks
Double quotation marks are used to keep the literal value of all characters in the quotation marks (carriage return is no exception), except in the following cases:
· $ The variable name can be used to get the value of the variable. The reverse quotation mark still indicates command replacement. \ $ indicates the $ literal name. \ 'indicates the' literal name. \ "indicates ". nominal value \ represents the nominal value. In addition to the preceding conditions, the '\' before other characters has no special meaning and only represents the literal value.$ Echo "$ SHELL"/bin/bash $ echo "'date'" Sun Apr 20 11:22:06 CEST 2003 $ echo "I 'd say: \ "Go for it \" "I 'd say:" Go for it "$ echo" \ "(Press ENTER)>" (Press enter again to end the command) "$ echo "\\"\
Ii. Shell script syntax

1. Conditional test: test [
The command test or [can test whether a condition is true. If the test result is true, the ExitStatus of the command is 0. If the test result is false, the Exit Status of the command is 1 (note that the logical representation of the C language is exactly the opposite ). For example, test the relationship between two numbers:
$ VAR = 2 $ test $ VAR-gt 1 $ echo $? 0 $ test $ VAR-gt 3 $ echo $? 1 $ [$ VAR-gt 3] $ echo $? 1Although it looks strange, the left square brackets[It is indeed a command name. The parameters passed to the command should be separated by spaces.For example, $ VAR,-gt, 3, and] are the four parameters of the [command. They must be separated by spaces. The test or [parameters are the same, but the test command does not need] parameters. Take the [command as an example. The following table lists common test commands:

Table 1.1. Test commands
[-D DIR]
True if DIR exists and is a directory
[-F FILE]
True if the FILE exists and is a normal FILE
[-Z STRING]
If the STRING length is zero, it is true.
[-N STRING]
True if the STRING length is not zero
[STRING1 = STRING2]
True if the two strings are the same
[STRING1! = STRING2]
True if the strings are different
[ARG1 OP ARG2]
ARG1 and ARG2 should be integers or variables with an integer value. OP is-eq (equal to)-ne (not equal to)-lt (less than)-le (less than or equal) -gt (greater than)-ge (greater than or equal)

Similar to the C language, the test conditions can also be compared with, or, non-logical operations:

Table 1.2. Test commands with and, or, not
[! EXPR]
EXPR can be any of the test conditions in the preceding table ,! Logical Inversion
[EXPR1-a EXPR2]
EXPR1 and EXPR2 can be any of the test conditions in the preceding table.-a indicates that
[EXPR1-o EXPR2]
EXPR1 and EXPR2 can be any of the test conditions in the preceding table.-o indicates the logic or

For example:
$ VAR = abc $ [-d Desktop-a $ VAR = 'abc'] $ echo $? 0Note: If the $ VAR variable in the previous example is not defined in advance, it is expanded as an empty string by Shell, it may cause syntax errors for test conditions (expanded to [-d Desktop-a = 'abc']). As a good Shell programming habit, always put the variable value in double quotation marks (expanded to [-d Desktop-a "= 'abc']):
$ Unset VAR $ [-d Desktop-a $ VAR = 'abc'] bash :[: too upload arguments $ [-d Desktop-a "$ VAR" = 'abc'] $ echo $? 1
2. if/then/elif/else/fi
Similar to the C language, the command if, then, elif, else, and fi are used in Shell to implement branch control. This process control statement is essentially composed of several Shell commands, as mentioned earlier
If [-f ~ /. Bashrc]; then .~ /. BashrcfiThere are actually three commands, if [-f ~ /. Bashrc] is the first, then .~ /. Bashrc is the second and fi is the third. If the two commands are written in the same line, they must be separated by a; number. If only one command is written in one line, no; number is required. In addition, there is a line break after then, but this command has not been written, shell will automatically continue the line and process the next line following then as a command. Like [commands, note that commands and parameters must be separated by spaces. The parameters of the if command form a sub-command. if the Exit Status of the sub-command is 0 (true), run the sub-command after then, if Exit Status is not 0 (false), run the subcommand after elif, else, or fi. The sub-commands after if are usually test commands, but can also be other commands. The Shell script does not have {} brackets, so fi is used 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 is NOT a file" fiif :; then echo "always true"; fi: It is a special command called an empty command. It does not do anything, but ExitStatus is always true. In addition, you can run/bin/true or/bin/false to obtain the true or false Exit Status. Let's look at another example:
#! /Bin/shecho "Is it morning? Please answer yes or no. "read YES_OR_NOif [" $ YES_OR_NO "=" yes "]; thenecho" Good morning! "Elif [" $ YES_OR_NO "=" no "]; thenecho" Good afternoon! "Elseecho" Sorry, $ YES_OR_NO not recognized. enter yes or no. "exit 1 fiexit 0 the read command in the above example is used to wait for the user to enter a string and store it in a Shell variable.
In addition, Shell also provides the & | syntax, which is similar to the C language and has the Short-circuit feature. Many Shell scripts like to write like this:
Test "$ (whoami )"! = 'Root' & (echo you are using a non-privileged account; exit 1) & equivalent to "if... then... ", and | equivalent to" if not... then... ". & | Used to connect two commands. The-a and-o mentioned above are only used to connect two test conditions in the test expression. Pay attention to their differences. For example,
Test "$ VAR"-gt 1-a "$ VAR"-lt 3 is equivalent to the following statement:
Test "$ VAR"-gt 1 & test "$ VAR"-lt 3
3. case/esac
The case command is similar to the switch/case statement in C language. esac indicates the end of the case statement block. The case in C language can only match the constant expressions of integer or numeric type, while the case in Shell script can match the string and Wildcard. Each matching branch can have several commands and must end, find the first matched branch during execution and execute the corresponding command. Then, Jump directly to esac without using break like the C language.
#! /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 example of using case statement can be in the script directory of the System Service/etc/init. d. Most scripts in this directory have this form (take/etc/apache2 as an example ):
Case $1 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; esacThe command to start the apache2 service is
$ Sudo/etc/init. d/apache2 start $1 is a special variable. It is automatically set to the first command line parameter (that is, start) when the script is executed. Similarly, if the command line parameter is set to stop, reload, or restart, you can go to another branch to run commands related to stopping the service, reloading the configuration file, or restarting the service.

4. for/do/done
The for loop structure of Shell scripts is very different from that of C language. It is similar to the foreach loop of some programming languages. For example:
#! /Bin/shfor FRUIT in apple banana pear; doecho "I like $ FRUIT" doneFRUIT is a cyclic variable. The value of $ FRUIT in the first loop is apple, banana in the second loop, and pear in the third loop. For another example, you need to change the names of chap0, chap1, and chap2 in the current directory to chap0 ~ , Chap1 ~ , Chap2 ~ ~ Character file name indicates a temporary file), this command can be written as follows:
$ For FILENAME in chap ?; Do mv $ FILENAME ~; DoneYou can also write as follows:
$ For FILENAME in 'ls chap? '; Do mv $ FILENAME ~; Done
5. while/do/done
The usage of while is similar to that of C. For example, a password verification script:
#! /Bin/shecho "Enter password:" read TRYwhile ["$ TRY "! = "Secret"]; doecho "Sorry, try again" read TRYdoneThe following example controls the number of cycles through arithmetic operations:
#! /Bin/shCOUNTER = 1 while ["$ COUNTER"-lt 10]; doecho "Here we go again" COUNTER =$ ($ COUNTER + 1) doneShell also has the until loop, similar to the do... while loop in C language. This chapter is omitted.

Exercise
1. Modify the password verification program. If the user fails to enter the password five times, the system reports an error and exits.

6. Location parameters and special Variables
Many special variables are automatically assigned values by Shell. We have met $? And $1. Here we will summarize:

Table 6.1 common location parameters and special Variables
$0
Equivalent to argv [0] of C main Function
$1, $2...
These are called PositionalParameter, which is equivalent to argv [1] and argv [2] of C main function...
$ #
It is equivalent to the argc-1 of the C main function. Note that # is not followed by a comment.
$ @
Indicates the parameter list "$1" "$2".... for example, it can be used after the in the for loop.
$?
Exit Status of the previous command
$
Process Number of the Current Shell

You can use the shift command to shift the location parameter to the left. For example, shift 3 indicates that the original $4 is changed to $1, and the original $5 is changed to $2. The original $1, $2, and $3 are discarded, and $0 is not moved. The shift command without parameters is equivalent to shift 1. For example:
#! /Bin/shecho "The program $0 is now running" echo "The first parameter is $1" echo "The second parameter is $2" echo "The parameter list is $ @" shiftecho "The first parameter is $1" echo "The second parameter is $2" echo "The parameter list is $ @"
7. Functions
Similar to the C language, Shell also has the function concept, but there is no return value or parameter list in the function definition. For example:
#! /Bin/shfoo () {echo "Function foo is called";} echo "-= start =-" fooecho "-= end = -"Note that there must be spaces or line breaks between the left curly braces {and the subsequent commands of the function body. If you write the last command and the right curly braces} on the same line, there must be a; sign at the end of the command. When defining the foo () function, you do not execute commands in the function body. Just like defining variables, you just need to define the foo name, when the foo function is called later (note that no parentheses are required for function calling in Shell), the command in the function body is executed. Functions in Shell scripts must be defined and called first. Generally, function definitions are written before the script, and function calls and other commands are written at the end of the script (similar to the main function in C language, this is where the entire script actually starts executing the command ).
If a Shell function does not have a list of parameters, it does not mean that parameters cannot be passed. In fact, a function is like a mini script. When a function is called, any parameter can be passed, $0, $1, and $2 are also used in the function to extract parameters. The location parameter in the function is equivalent to the local variable of the function, changing these variables does not affect $0, $1, $2, and other variables outside the function. You can use the return command to return a function. If return is followed by a number, it indicates the Exit Status of the function.
The following script creates multiple directories at a time. Each directory name is passed in through the command line parameter. The script tests each directory one by one to check whether the directory exists. If the directory does not exist, print the information and try to create the directory.
#! /Bin/shis_directory () {DIR_NAME = $ 1if [! -D $ DIR_NAME]; then return 1 else return 0fi} for DIR in "$ @"; doif 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 using idoneNOTE: If is_directory () is returned, 0 indicates that true returns 1 indicates false.

How to debug a three Shell script
Shell provides some options for script debugging, as shown below:
-N: reads the commands in the script but does not execute the command. It is used to check the syntax errors in the script.-Run the script on the vone side, one side prints the executed script command to the standard error output-x provides the trace execution information and prints each command and result in sequence. There are three methods to use these options, first, provide parameters in the command line.
$ Sh-x./script. shSecond, provide parameters at the beginning of the script
#! /Bin/sh-xThe third method is to use the set command in the script to enable or disable parameters.
#! /Bin/shif [-z "$1"]; thenset-xecho "ERROR: Insufficient Args." exit 1 set + xfiSet-x and set + x indicate to enable and disable the-x parameter, respectively, so that you can only trace and debug a part of the script.

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.