1, shell variable
1. Define variables
Shell supports the following three ways to define variables
xub$ name=value xub$ name='value' xub$ name="value" # Name is the variable name and value is the value assigned to the variable.
difference
If value does not contain any white space characters (such as spaces, Tab indents, etc.), quotation marks can not be used;
If value contains whitespace, it must be enclosed in quotation marks.
There is also a difference between using single quotation marks and using double quotation marks.
Note that there must be no spaces on either side of the assignment number =.
xub$ name="Small" #assignment xub$ echo $name #Output command xub$ Small #output
2. Use variables
To use a defined variable, just add the dollar sign $in front of the variable name, such as:
xub$ home="Qiandao Lake" xub$ echo $home Qiandao Lake xub$ echo ${home} Qiandao Lake
The curly bracket {} outside the variable name is optional. It can be added or not. The curly bracket is added to help the interpreter identify the boundary of the variable, such as the following:
xub$ name="xiaoxaio" xub$ echo "my name is $namecc " my name is #Because there is no system variable name found here
Change to
xub$ name="xiaoxaio" xub$ echo "my name is ${name}cc " my name is xiaoxaiocc #This is the advantage of ${}
3. The difference between single quotation marks and double quotation marks
As mentioned above, when defining a variable, the value of the variable is different from the single quotation mark '' and the double quotation mark '', for example:
xub$ sex="female" xub$ one='The little gender is: ${sex}' xub$ two="The little gender is: ${sex}" xub$ echo $one The little gender is: ${sex} xub$ echo $two The little gender is: female
difference
- When the value of a variable is enclosed in single quotation marks', whatever is in the single quotation marks will be output. Even if there are variables and commands in the content (the commands need to be quoted back), they will be output as they are.
- When enclosing the value of a variable with double quotation marks "", the variables and commands inside will be parsed first when outputting, rather than outputting the variable name and commands in double quotation marks as they are.
Recommendations:
1) If the content of the variable is a number, it can be without quotation marks;
2) If you really need to output as is, add single quotation marks;
3) Other strings without special requirements are best enclosed in double quotation marks.
4. Read only variable
Use the readonly command to define a variable as a read-only variable. The value of a read-only variable cannot be changed.
xub$ name=zhangsan;readonly name;name=lisi #Here are three commands; separate -bash: name: readonly variable #report errors
5. Delete variable
Use the unset command to delete variables. Syntax:
xub$ unset variable_name
Note that the unset command cannot delete read-only variables.
6. Assign the output of the command to a variable
Shell also supports assigning the execution result of a command to a variable. There are two common methods:
xub$ name=`return` xub$ name=$(return)
The first way is to enclose the command with back quotation marks (located below the Esc key). Back quotation marks are very similar to single quotation marks, which is easy to be confused, so this method is not recommended; The second way is to surround the command with $(), which makes the distinction more obvious. Therefore, this way is recommended.
Example 1
xub$ name=$(cat name.text) #Name Text file content assigned to name xub$ echo $name #output Hello, everyone. My name is Xiaoxiao
For example 2, the date command is used to obtain the current system time. Using the command replacement, its result can be assigned to a variable.
xub$ begin_time=`date` #Start time, replace with ` ` xub$ sleep 20s #Sleep for 20 seconds xub$ finish_time=$(date) #End time, replace with $() xub$ echo "Begin time: $begin_time" Begin time: 2019 Thursday, May 16, 2004 22:37:46 CST xub$ echo "Finish time: $finish_time" Finish time: 2019 Thursday, May 16, 2006 22:38:06 CST
The current UNIX timestamp can be obtained by using the% s format controller of the data command, so that the running time of the script can be calculated directly.
xub$ begin_time=`date +%s` #Start time, replace with ` ` xub$ sleep 5s #Sleep for 5 seconds xub$ finish_time=$(date +%s) #End time, replace with $() xub$ run_time=$((finish_time - begin_time)) #time difference xub$ echo "begin time: $begin_time" begin time: 1558017925 xub$ echo "finish time: $finish_time" finish time: 1558017930 xub$ echo "run time: ${run_time}s" run time: 5s
Note: if the output content of the replaced command includes multiple lines (i.e. line breaks) or contains multiple consecutive white space characters, the variable should be enclosed in double quotation marks when outputting the variable, otherwise the system will use the default white space character to fill in, which will lead to invalid line breaks and the continuous white space characters will be compressed into one. See the following code:
xub$ ls=`ls -l | grep damo` xub$ echo $ls #Do not use double quotation marks drwxr-xr-x 16 xub staff 544 5 15 14:27 adamo drwxr-xr-x 4 xub staff 136 3 21 17:27 damo xub$ echo "$ls" #Enclose with double quotation marks drwxr-xr-x 16 xub staff 544 5 15 14:27 adamo #It is found that double quotation marks are used to separate the contents of variables drwxr-xr-x 4 xub staff 136 3 21 17:27 damo
summary
In principle, the two forms of variable substitution mentioned above are equivalent and can be used at will; However, after all, backquotes look like single quotes, which sometimes makes it difficult to view the code
(
)
Just
mutually
yes
clear
Clear
,
can
have
effect
avoid
Exempt
this
species
mix
chaos
.
and
And
have
some
feeling
condition
have to
must
send
use
it
,
because
by
it
branch
hold
Inlay
set
,
back
lead
number
no
that 's ok
.
with
Time
also
want
notes
meaning
() is relatively clear, which can effectively avoid this confusion. In addition, it must be used in some cases because it supports nesting and backquotes do not work. Also pay attention to
() is relatively clear, which can effectively avoid this confusion. In addition, it must be used in some cases because it supports nesting and backquotes do not work. Also note that () is only valid in Bash shells, while backquotes can be used in a variety of shells.
2, Shell location parameters
When running the Shell script file, we can pass some parameters to it. These parameters can be received in the form of $n inside the script file. For example, $1 represents the first parameter, $2 represents the second parameter, and so on.
This parameter received in the form of $n is called location parameter in Shell.
1. Pass location parameters to script files
Please write the following code and name it family sh
#!/bin/bash # $1 represents receiving the first parameter passed in, $2 represents the second parameter echo "name: $1" echo "sex: $2"
Run family sh
xub$ sh family.sh Little 3 years old #Pass in two parameters separated by spaces name: Small #output sex: 3 year
2. Passing positional parameters to a function
Also create family SH script
#!/bin/bash #Define function function func(){ echo "name: ${1}" echo "age: ${2}" } #Call function func Little 3 years old
Run family SH script
xub$ sh family.sh #Run script name: Small #output age: 3 year
be careful
If the number of parameters is too many, reaching or exceeding 10, you have to use
n
of
shape
type
come
meet
collect
Yes
,
example
as
'
{n} Received in the form of, for example`
Received in the form of n, such as' {10}, '. The function of {} is to help the interpreter identify the boundary of parameters, which has the same effect as adding {} when using variables.
3, Shell special variables and their meanings
variable | meaning |
---|---|
$0 | The file name of the current script |
$n(n≥1) | Parameters passed to a script or function. n is a number indicating the number of parameters. For example, the first parameter is $1 and the second parameter is $2 |
$# | The number of parameters passed to the script or function |
$* | All parameters passed to a script or function |
$@ | All parameters passed to a script or function. When enclosed in double quotation marks, "$@ is slightly different from $*. We will ∗ and *And * and @ |
$? | The exit status of the last command or the return value of the function will be described in Shell $ In the next section |
$$ | Current Shell process ID. For Shell scripts, it is the process ID where these scripts are located |
Let's demonstrate it with two examples.
1. Pass parameters to script file
Write the following code and save it as family sh
#!/bin/bash echo "current shell process ID: $$" echo "Parameter name 0: $0" echo "First parameter name: $1" echo "Second parameter name: $2" echo "All parameter names output mode I: $@" echo "All parameter names output mode 2: $*" echo "The number of parameters passed to the script or function: $#"
Run family sh
xub$ sh family.sh Zhang San, Wang Laowu #Run script current shell process ID: 38745 Parameter name 0: family.sh First parameter name: Zhang San Second parameter name: bachelor All parameter names output mode I: Zhang San, Wang Laowu All parameter names output mode 2: Zhang San, Wang Laowu The number of parameters passed to the script or function: 2
2. Pass parameters to function
Write the following code and save it as family sh
#!/bin/bash #Define function function fun(){ echo "current shell process ID: $$" echo "Parameter name 0: $0" echo "First parameter name: $1" echo "Second parameter name: $2" echo "All parameter names output mode I: $@" echo "All parameter names output mode 2: $*" echo "The number of parameters passed to the script or function: $#" } fun Li Si, Zhao Liu
Run family sh
xub$ sh family.sh current shell process ID: 40243 Parameter name 0: family.sh First parameter name: Li Si Second parameter name: Zhao Liu All parameter names output mode I: Li Si, Zhao Liu All parameter names output mode 2: Li Si, Zhao Liu The number of parameters passed to the script or function: 2
3. The difference between Shell $* and $@
Similarities: $* and $@ represent all parameters passed to a function or script. When $* and $@ are not surrounded by double quotation marks "", there is no difference between them. Each parameter received is regarded as a piece of data, separated by spaces.
Differences: however, when they are enclosed in double quotation marks' ', there will be differences:
"$*"All parameters will be regarded as a piece of data as a whole, rather than each parameter as a piece of data. "$@"Each parameter is still regarded as a piece of data, which is independent of each other.
For example, if five parameters are passed“ ∗ " come say , this 5 individual ginseng number meeting close and reach one rise shape become one share number according to , it Men of between yes nothing method branch cut of ; and yes to " *"For example, these five parameters will be combined to form a data, and they cannot be separated; for" * for "@", these five parameters will be combined to form a piece of data, and they are inseparable; for "@", these five parameters are independent of each other, and they are five pieces of data.
If you use echo to directly output "$*" and "$@" for comparison, you can't see the difference; But if you use the for loop to output data one by one, you can immediately see the difference.
Examples
Write the following code and save it as test sh
#!/bin/bash echo "Start traversing parameters from \"\$*\"" for var in "$*" do echo "$var" done echo "Start traversing parameters from \"\$@\"" for var in "$@" do echo "$var" done
Run test SH with parameters:
xub$ sh test.sh Little mom and Dad Start traversing parameters from "$*" #Obviously, $* takes the parameters I've inserted as a whole Little mom and Dad Start traversing parameters from "$@" # The arguments passed in from $@ are independent of each other Small dad mom
It can be found from the running results that "$*" is only cycled once because it has only 1 point of data; For "$@", it loops three times because it has three copies of data.
4, Shell $?
$? Is a special variable used to obtain the exit status of the previous command or the return value of the previous function.
The so-called exit status is the return result after the execution of the last command. The exit status is a number. Generally, most commands will return 0 if they are executed successfully and 1 if they fail. However, some commands return other values, indicating different types of errors.
1,$? Gets the exit status of the previous command
Write the following code and save it as test sh:
#!/bin/bash if [ "$1" == 100 ] then exit 0 #The parameter is correct and the exit status is 0 else exit 1 #Parameter error, exit status 1 fi
Exit means to exit the current Shell process. We must run test in the new process SH, otherwise the current Shell session (terminal window) will be closed, and we can't get its exit status.
For example, run test Pass parameter 100 when sh:
xub$ bash ./test.sh 100 #Run as a new process xub$ echo $? 0
As another example, run test Pass parameter 89 when sh:
xub$ bash ./test.sh 89 #Run as a new process xub$ echo $? 1
2, $? Gets the return value of the function
Write the following code and save it as test sh:
#!/bin/bash #Get the sum of the two numbers function add(){ return `expr $1 + $2` } add 23 50 #Call function echo $? #Get function return value
Operation results 73
Note: strictly speaking, the return keyword in the Shell function is used to indicate the exit status of the function, not the return value of the function; Unlike other programming languages, Shell does not have keywords that specifically deal with return values.
I hope this article is helpful to you ~ ~ if you are interested in interface testing, automated testing and interview experience, you can join us. 642830685, get the latest software testing factory interview materials and Python automation, interface and framework building learning materials for free! Technical cattle solve doubts and answer questions, and communicate with peers.