Shell scripting thing 7

Seven, special variables

As mentioned earlier, variable names can only contain numbers, letters and underscores, because some variables containing other characters have special meanings, and such variables are called special variables.

For example, $ represents the ID of the current Shell process, that is, pid, see the following code: 

 

 

list of special variables

variable

meaning

$0

filename of the current script

$n

Arguments passed to scripts or functions. n is a number indicating the number of parameters. For example, the first argument is $1 and the second argument is $2.

$#

The number of arguments passed to the script or function.

$*

All arguments passed to the script or function.

$@

All arguments passed to the script or function. When enclosed in double quotes (" "), it is slightly different from $*, which will be described below.

$?

The exit status of the last command, or the return value of a function.

$$

Current shell process ID. For shell scripts, the process ID in which the scripts reside.

command line arguments

The arguments passed to the script when it is run are called command line arguments. Command-line arguments are represented by $n, ​​for example, $1 for the first argument, $2 for the second argument, and so on.

See the script below: 

 

 

Difference between $* and $@

Both $* and $@ represent all arguments passed to a function or script, and when not enclosed in double quotes (" "), all arguments are output as "$1" "$2" … "$n".

But when they are enclosed in double quotes (" "), "$*" will output all parameters as a whole in the form of "$1 $2 ... $n"; "$@" will separate the parameters, Output all arguments as "$1" "$2" … "$n".

The following example can clearly see the difference between $* and $@: 


Execute ./sh7_2.sh 1 2 3 4 5 and see the following result:


exit status

$? can get the exit status of the previous command. The so-called exit status is the return result after the execution of the previous command.

The exit status is a number. In general, most commands will return 0 if they are successfully executed, and 1 if they fail.

However, there are some commands that return other values, indicating different types of errors.

In the following example, the command executes successfully: 


$? can also represent the return value of a function, which will be explained later.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325945754&siteId=291194637