In the previous section we talked about $n, which is a special variable used to receive positional parameters. In this section, we will continue to explain the remaining special variables, namely: $#, $*, $@, $?, $$.
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 that represents the parameter. For example, the first parameter is $1 and the second parameter is $2. |
$# | The number of parameters passed to a script or function. |
$* | All parameters passed to a script or function. |
$@ | All parameters passed to a script or function. When included in double quotes "", $@ is slightly different from $*, we will use "The difference between Shell $* and $@》 section explains in detail. |
$? | The exit status of the previous command, or the return value of the function, we will use theShell $?》 section explains in detail. |
$$ | Current Shell process ID. For shell scripts, it is the process ID where these scripts are located. |
Let’s demonstrate it through two examples below.
1) Pass parameters to the script file
Write the following code and save it as:
#!/bin/bash echo "Process ID: $$" echo "File Name: $0" echo "First Parameter : $1" echo "Second Parameter : $2" echo "All parameters 1: $@" echo "All parameters 2: $*" echo "Total: $#"
Run with parameters:
[mozhiyan@localhost demo]$ . ./ Shell Linux
Process ID: 5943
File Name: bash
First Parameter : Shell
Second Parameter : Linux
All parameters 1: Shell Linux
All parameters 2: Shell Linux
Total: 2
2) Pass parameters to the function
Write the following code and save it as:
#!/bin/bash #Define functionsfunction func(){ echo "Language: $1" echo "URL: $2" echo "First Parameter : $1" echo "Second Parameter : $2" echo "All parameters 1: $@" echo "All parameters 2: $*" echo "Total: $#" } #Calling functionsfunc Java /java/
The running result is:
Language: Java
URL: /java/
First Parameter : Java
Second Parameter : /java/
All parameters 1: Java /java/
All parameters 2: Java /java/
Total: 2
This is the article about the use of Shell special variables (Shell $#, $*, $@, $?, $$) here. For more relevant Shell special variable content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!