shell 位置参量和命令行参数

一、位置参量

用户可以通过命令行向脚本传递信息。跟在脚本名后的用空白符分隔的每个词都被称为参数。
我们可以在脚本中使用位置参量来引用命令行参数,例如,$1 代表第 1 个参数,$2 代表第 2 个参数,$3 代表第 3 个参数,以此类推。$9 以后,要使用花括号把数字括起来,以表示一个两位数,例如,第 10 个位置参量以 ${10} 的方式来访问。变量 $# 可以被用来表示参量的个数,而 $* 则代表所有的参量。我们可以用 set 命令来设置或重设位置参量。如果使用了 set 命令,之前设置的所有位置参量都会被清空。

位置参量指代对象
$0脚本名
$#位置参量个数
$*所有的位置参量
$@未加双引号时,与 $* 的含义相同
“$*”单个变量(例如:"$1 $2 $3")
“$@”多个单独的变量(例如:"$1" “$2” “$3”)
$1 … ${10}单独的位置参量
[root@localhost ~]# chmod +x greeting2 
[root@localhost ~]# cat greeting2 
#! /bin/bash
# Scriptname: greeting2
echo "This script is called $0."
echo "$0 $1 and $2"
echo "The number of positional parameters is $#"
[root@localhost ~]# ./greeting2 
This script is called ./greeting2.
./greeting2  and 
The number of positional parameters is 0
[root@localhost ~]# 
[root@localhost ~]# ./greeting2  Tommy
This script is called ./greeting2.
./greeting2 Tommy and 
The number of positional parameters is 1
[root@localhost ~]# 
[root@localhost ~]# ./greeting2  Tommy Kimberly
This script is called ./greeting2.
./greeting2 Tommy and Kimberly
The number of positional parameters is 2
[root@localhost ~]# 

二、set 命令与位置参量

带参数的 set 命令将重置位置参量。位置参量一旦被重置,原来的参量列表就丢失了。要想清除所有的位置参量,可使用 set – 命令。$0 始终指代脚本名。

[root@localhost ~]# cat args           
#!/bin/bash
# Scriptname: args
# Script to test command-line arguments
echo The name of this script is $0.
echo The arguments are $*.
echo The first arguments is $1.
echo The second arguments is $2.
echo The number of arguments is $#.
oldargs=$*
set Jake Nicky Scott #Reset the positional parameters
echo All the positional parameters are $*.
echo The number of positional parameters is $#.
echo "Good-bye for now,$1."
set $(date) #Reset the positional parameters
echo The date is $2 $3, $6.
echo "The value of \$oldargs is $oldargs."
set $oldargs
echo $1 $2 $3
[root@localhost ~]# ./args a b c d
The name of this script is ./args.
The arguments are a b c d.
The first arguments is a.
The second arguments is b.
The number of arguments is 4.
All the positional parameters are Jake Nicky Scott.
The number of positional parameters is 3.
Good-bye for now,Jake.
The date is Mar 30, 2022.
The value of $oldargs is a b c d.
a b c
[root@localhost ~]# 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值