假设我要运行一个可以携带参数的 script ,运行该脚本后萤幕会显示如下的数据:
- 程序的档名为何?
- 共有几个参数?
- 若参数的个数小於 2 则告知使用者参数数量太少
- 全部的参数内容为何?
- 第一个参数为何?
- 第二个参数为何
#!/bin/bash
#The program shows the script name,and the parameters....
echo "The script name is ==> $0"
echo "The num of the parameters is ==>$#"
[ $# -lt 2 ] && echo "The num is less than 2. Stop here!" && exit 0
echo "The whole parameter is ==> '$@'"
echo "The 1st parameter is ==>$1"
echo "The 2nd parameter is >$2"
执行脚本:
[oracle@SOR_SYS~]$ sh parameters.sh opt1 oracle 192.168.50.229 8081
The script name is ==> parameters.sh
The num of the parameters is ==>4
The whole parameter is ==> 'opt1 oracle 192.168.50.229 8081'
The 1st parameter is ==>opt1
The 2nd parameter is >oracle
[oracle@SOR_SYS~]$
- $# :代表后接的参数『个数』,以上表为例这里显示为『 4 』;
- $@ :代表『 "$1" "$2" "$3" "$4" 』之意,每个变量是独立的(用双引号括起来);
- $* :代表『 "$1c$2c$3c$4" 』,其中 c 为分隔字节,默认为空白键, 所以本例中代表『 "$1 $2 $3 $4" 』之意。
本文介绍了一个Bash脚本,该脚本能够展示如何获取并解析传递给它的命令行参数。通过此脚本,用户可以了解到如何使用特殊变量$0、$#、$@和$*来分别获取脚本名称及所有参数的个数与内容。
1万+

被折叠的 条评论
为什么被折叠?



