$0 $1 $# $@ $* $? Meaning in Linux

1. $0, $1, $2,..., $n

$0 : This special point indicates the name of the command itself.
$1  indicates the first parameter.
$2 : indicates the second parameter.
$n : indicates the nth parameter.

[root@localhost shell]# cat test01.sh 
echo $0
echo $1
echo $2
[root@localhost shell]# ./test01.sh Hello World
./test01.sh
Hello
World
[root@localhost shell]# bash test01.sh Hello World
test01.sh
Hello
World

Two, $#

$# : Represents the actual number of parameters

[root@localhost shell]# cat test02.sh 
echo "length is " $#
[root@localhost shell]#bash test02.sh 1 2 aa bb
length is  4

Three, $$

$$ : represents the pid of the current process

[root@localhost shell]# cat test03.sh 
echo "my pid is " $$
[root@localhost shell]# bash test03.sh 
my pid is  47282
[root@localhost shell]# echo $$
46946

Four, $?

$?: Indicates the exit status of the previous command execution ( 0 means no error, other means there is an error )

[root@localhost shell]# cat test.sh 
exit 66 
[root@localhost shell]# ./test.sh 
[root@localhost shell]# echo $?
66

Five, $!

$!: Represents the pid of the most recent background execution program

[root@localhost shell]# sleep 60 &
[1] 47395
[root@localhost shell]# sleep 70 &
[2] 47396
[root@localhost shell]# echo $!
47396

Six, other

$
-List of Flags set with the Set command.
$* List of 
all parameters. If "$*" is enclosed in """, all parameters are output in the form of "$1 $2… $n". 
$@
All parameter list. If "$@" is enclosed in """, all parameters are output in the form of "$1" "$2"… "$n". 

The difference between $* and $@:

  • The same point: all parameters are quoted.
  • Difference: only reflected in double quotes. Assuming that three parameters 1, 2, 3 are written when the script is running, "*" is equivalent to "1 2 3" (a parameter is passed), and "@" is equivalent to "1" "2" " 3" (Three parameters are passed).

Seven, summary

vim test.sh

#!/bin/sh 
echo "number:$#" 
echo "scname:$0" 
echo "first :$1" 
echo "second:$2" 
echo '     -----$*'
for i in "$*"; do
    echo $i
    done

echo '     -----$@'
for i in "$@"; do
    echo $i
    done
echo "PID:$$"

bash test.sh aa bb cc

Reference link: https://www.runoob.com/linux/linux-shell-passing-arguments.html

 

Guess you like

Origin blog.csdn.net/l_liangkk/article/details/105649018