Shell script 的默认变量($0, $1...)

来源:互联网 发布:取消windows启动管理器 编辑:程序博客网 时间:2024/06/05 11:49

 

 假设我要运行一个可以携带参数的 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" 』之意。

 

原创粉丝点击