1. Used in shell scripts#
Indicates the annotation, which is equivalent to the C Language//
Annotations. However, if#
Located at the beginning of the first line, and is#!
(Shebang) is an exception. It indicates that the script uses the interpreter specified later./bin/sh
Explain execution
$ chmod +x script.sh$ ./script.sh
2. Two Methods for executing shell scripts:
$ ./script.sh$ sh ./script.sh
3. Multiple commands separated by semicolons can be entered in one line.
$ cd ..;ls -l
4. It only exists in the current shell process.set
Command to display all variables (including local 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 and is usedexport
You can use the following command to export local variables as environment variables:
$ export VARNAME=value
You can also do this in two steps:
$ VARNAME=value$ export VARNAME
Useunset
Command to delete the defined environment variables or local variables.
$ unset VARNAME
If a variable is calledVARNAME
, Use${VARNAME}
It can represent its value. It can also be used without ambiguity.$VARNAME
It indicates its value. The following example compares the differences between the two representations:
$ echo $SHELL$ echo $SHELLabc$ echo $SHELL abc$ echo ${SHELL}abc
Note: $ 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 values of shell variables are strings. For example, we defineVAR=45
In factVAR
The 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.
5. Single quotes and double quotation marks in shell scripts are the same as character 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
6. 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 Storagedate
Command output:
$ DATE=`date`$ echo $DATE
Command replacement can also be used$()
Indicates:
$ DATE=$(date)
7,
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:
$ You can add a variable name to get the value of the variable.
Reverse quotation marks still indicate command replacement
\ $ Indicates the nominal value of $
\ 'Indicates the literal value'
The nominal value of \ "represents ".
\ Represents the literal value \
In addition to the preceding conditions, the '\' before other characters has no special meaning and only indicates 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 "\\"\
8. Startbash
The following script is automatically executed:
Run/etc/profile
Every user in the system needs to execute this script upon logon. If the system administrator wants a setting to take effect for all users, write it in this script.
Search for~/.bash_profile
,~/.bash_login
And~/.profile
Find the first file that exists and is readable for execution. If you want a setting to only take effect for the current user, you can write it in this script./etc/profile
Then execute,/etc/profile
The value of some environment variables can be modified in this script, that is, the current user's settings can overwrite the global settings in the system.~/.profile
The STARTUP script issh
Specified,bash
It is required to first search~/.bash_
Start script. If not, run~/.profile
To matchsh
Always consistent.
By the way~/.bash_logout
Script (if it exists ).
9. Test
Commandtest
Or[
You can test whether a condition is true. If the test result is true, the exit status 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 $?1
Although 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
,]
Yes[
Command, which must be separated by spaces. Commandtest
Or[
The parameter format is the same,test
Command not required]
Parameters. To[
For example, the following table lists common test commands:
[ -d DIR ] |
IfDIR If a directory exists and is true |
[ -f FILE ] |
IfFILE If a common file exists, it is true. |
[ -z STRING ] |
IfSTRING The length of 0 is true. |
[ -n STRING ] |
IfSTRING The non-zero length is true. |
[ STRING1 = STRING2 ] |
True if the two strings are the same |
[ STRING1 != STRING2 ] |
True if the strings are different |
[ ARG1 OP ARG2 ] |
ARG1 AndARG2 It should be an integer or a variable with an integer value,OP Yes-eq (Equal)-ne (Not equal)-lt (Less)-le (Less than or equal)-gt (Greater)-ge (Greater than or equal) |
Similar to the C language, the test conditions can also be compared with, or, non-logical operations:
Test commands with or, or, not
[ ! EXPR ] |
EXPR It can be any test condition in the preceding table ,! Logical Inversion |
[ EXPR1 -a EXPR2 ] |
EXPR1 AndEXPR2 It can be any test condition in the preceding table,-a Representation logic and |
[ EXPR1 -o EXPR2 ] |
EXPR1 AndEXPR2 It can be any test condition in the preceding table,-o Indicates logic or |
For example:
$ VAR=abc$ [ -d Desktop -a $VAR = 'abc' ]$ echo $?0
Note: If$VAR
If the variable is not defined in advance, the shell expands to an empty string, causing a syntax error in the test condition (expanded[ -d Desktop -a = 'abc' ]
As a good shell programming habit, the variable value should always be placed in double quotation marks (expanded[ -d Desktop -a "" = 'abc' ]
):
$ unset VAR$ [ -d Desktop -a $VAR = 'abc' ]bash: [: too many arguments$ [ -d Desktop -a "$VAR" = 'abc' ]$ echo $?1
10. Case/esac
case
Commands can be analogous to Cswitch
/case
Statement,esac
Indicatescase
The end of the statement block. C Languagecase
Only constant expressions of integer or struct type can be matched.case
It can match the string and wildcard. Each matching branch can have several commands and must end with;. When executing the command, locate the first matching branch and execute the corresponding command, and then jump directlyesac
Later, you do not need to usebreak
Jump out.
#! /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
Usecase
The statement example can be found in the script directory of the system service./etc/init.d
. Most scripts in this directory have this form (/etc/apache2
For example ):
case $1 instart)...;;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
Startapache2
The service command is
$ sudo /etc/init.d/apache2 start
$1
Is a special variable. It is automatically set to the first command line parameter during script execution, that isstart
, So enterstart)
Branch to execute related commands. Similarly, the command line parameter is specifiedstop
,reload
Orrestart
You can go to other branches to execute commands related to stopping the service, re-loading the configuration file, or restarting the service.
11. If fi
Similar to C, it is used in Shellif
,then
,elif
,else
,fi
These commands implement branch control. This process control statement is essentially composed of several shell commands, as mentioned earlier
if [ -f ~/.bashrc ]; then . ~/.bashrcfi
There are actually three commands,if [ -f ~/.bashrc ]
Is the first,then . ~/.bashrc
Is the second,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,then
There is a line break later, but this command is not completed, shell will automatically continue the line, the next line is connectedthen
It is processed as a command. And[
Commands are the same. Note that the commands and parameters must be separated by spaces.if
Command Parameters constitute a sub-command. If the exit status of the sub-command is 0 (true ),then
Subcommand. If exit status is not 0 (false), runelif
,else
Orfi
Subcommands.if
The following sub-commands are usually test commands, but can also be other commands. Shell script does not have {} brackets, so usefi
Indicatesif
The end of the 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 the exit status is always true. You can also execute/bin/true
Or/bin/false
Returns 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" ]; 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
In the above exampleread
The function of the command is 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)
& Is equivalent to "If... then...", and | is equivalent to "if not... then ...". & | Used to connect two commands.-a
And-o
It is only used to connect two test conditions in a test expression. Pay attention to their differences, for example,
test "$VAR" -gt 1 -a "$VAR" -lt 3
It is equivalent to the following statement:
test "$VAR" -gt 1 && test "$VAR" -lt 3