Linux传递位置参数,Linux-scripts-位置参数等特殊变量

本文详细介绍了Shell脚本中的默认变量,如$0表示脚本名,$n(n>=1)代表参数,$#表示参数个数,$*和$@用于传递所有参数,$?给出上个命令的退出状态,$$则为当前Shell进程ID。通过实例展示了如何使用这些变量以及`shift`命令来处理脚本参数。
摘要由CSDN通过智能技术生成

9.Scripts

9.3.3 Shell script的默认变数($0, $1...)变量含义

$0当前脚本的文件名。

$n(n≥1)传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是 $1,第二个参数是 $2。

$#传递给脚本或函数的参数个数。

$*传递给脚本或函数的所有参数。

$@传递给脚本或函数的所有参数。

$?上个命令的退出状态,或函数的返回值。

$$当前   Shell 进程 ID。对于 Shell 脚本,就是这些脚本所在的进程 ID。

注:

n$@ :代表『 "$1" "$2" "$3" "$4" 』之意,每个变量是独立的(用双引号括起来);

n$* :代表『 "$1c$2c$3c$4" 』,其中 c 为分隔字符,默认为空格键,所以本例中代表『 "$1 $2 $3 $4" 』之意。

1.实例

[root@localhost tmp]# vim 1.sh

#!/bin/bash

echo "The script name is        ==> ${0}"

echo "Total parameter number is ==> $#"

[ "$#" -lt 2 ] && echo "The number of parameter is less than 2.  Stop here." && exit 0

echo "Your whole parameter is   ==> '$@'"

echo "The 1st parameter         ==> ${1}"

echo "The 2nd parameter         ==> ${2}"

[root@localhost tmp]# sh 1.sh a b c d

The script name is        ==> 1.sh

Total parameter number is ==> 4

Your whole parameter is   ==> 'a b c d'

The 1st parameter         ==> a

The 2nd parameter         ==> b

[root@localhost tmp]# ./1.sh a b c d

The script name is        ==> ./1.sh

Total parameter number is ==> 4

Your whole parameter is   ==> 'a b c d'

The 1st parameter         ==> a

The 2nd parameter         ==> b

2.shift:造成参数变量号码偏移

[root@localhost tmp]# vim shift.sh

#!/bin/bash

echo "Total parameter number is ==> $#"

echo "Your whole parameter is   ==> '$@'"

shift   # 进行第一次『一个变量的 shift 』

echo "Total parameter number is ==> $#"

echo "Your whole parameter is   ==> '$@'"

shift 3 # 进行第二次『三个变量的 shift 』

echo "Total parameter number is ==> $#"

echo "Your whole parameter is   ==> '$@'"

[root@localhost tmp]# sh shift.sh a b c d e f g

Total parameter number is ==> 7

Your whole parameter is   ==> 'a b c d e f g'

Total parameter number is ==> 6

Your whole parameter is   ==> 'b c d e f g'

Total parameter number is ==> 3

Your whole parameter is   ==> 'e f g'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值