Skip to content

特殊变量

$n

1)基本语法

shell
$n (功能描述:n 为数字,$0 代表该脚本名称,$1-$9 代表第一到第九个参数,十以 上的参数,十以上的参数需要用大括号包含,如${10}

2)案例实操

shell
[root@centos7 sh]# touch parameter.sh
[root@centos7 sh]# vim parameter.sh 
#!/bin/bash
echo '==========$n=========='
echo $0
echo $1
echo $2
[root@centos7 sh]# chmod 777 parameter.sh 
[root@centos7 sh]# ./parameter.sh cls xz
[root@centos7 sh]# ./parameter.sh cls xz hh
==========$n=============
./parameter.sh
cls
xz

$#

1)基本语法

shell
 $# (功能描述:**获取所有输入参数个数**,常用于循环,判断参数的个数是否正确以及 加强脚本的健壮性)。

2)案例实操

shell
[root@centos7 sh]# vim parameter.sh
#!/bin/bash
echo '==========$n=========='
echo $0
echo $1
echo $2
echo '==========$#=========='
echo $#
[root@centos7 sh]# chmod 777 parameter.sh
[root@centos7 sh]# ./parameter.sh cls xz
==========$n==========
./parameter.sh
cls
xz
==========$#==========
2

$*、$ @

1)基本语法

shell
$* (功能描述:这个变量代表命令行中所有的参数,$*把所有的参数看成一个整体)
$@ (功能描述:这个变量也代表命令行中所有的参数,不过$@把每个参数区分对待)

2)案例实操

shell
[root@centos7 sh]# vim parameter.sh
#!/bin/bash
echo '==========$n=========='
echo $0
echo $1
echo $2
echo '==========$#=========='
echo $#
echo '==========$*=========='
echo $*
echo '==========$@=========='
echo $@
[root@centos7 sh]# ./parameter.sh a b c d e f g
==========$n==========
./parameter.sh
a
b
==========$#==========
7
==========$*==========
a b c d e f g
==========$@==========
a b c d e f g

$?

1)基本语法

shell
  $? (功能描述:最后一次执行的命令的返回状态。如果这个变量的值为 0,证明上一 个命令正确执行;如果这个变量的值为非 0(具体是哪个数,由命令自己来决定),则证明 上一个命令执行不正确了。)

1)基本语法

shell
  $? (功能描述:最后一次执行的命令的返回状态。如果这个变量的值为 0,证明上一 个命令正确执行;如果这个变量的值为非 0(具体是哪个数,由命令自己来决定),则证明 上一个命令执行不正确了。)

2)案例实操

判断 helloworld.sh 脚本是否正确执行

shell
[root@centos7 sh]# ./helloworld.sh
hello world
[root@centos7 sh]# echo $?
0