码迷,mamicode.com
首页 > 系统相关 > 详细

linux shell变量$#,$@,$0,$1,$2的含义解释

时间:2015-07-29 00:36:52      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

变量说明: 
$$ Shell本身的PID(ProcessID) 
$! Shell最后运行的后台Process的PID 
$? 最后运行的命令的结束代码(返回值) 
$- 使用Set命令设定的Flag一览 
$* 所有参数列表。 所有的参数被认为是一个字符串
$@ 所有参数列表。参数是独立的字符串
$# 添加到Shell的参数个数 
$0 Shell本身的文件名 
$1~$n 添加到Shell的各参数值。$1是第1个参数、$2是第2个参数…。 

通过一个脚本,来看看各个变量的效果

 1 #!/bin/sh
 2 
 3 ## RustFisher
 4 
 5 echo "----------------------"
 6 echo "PID:            \$$  $$"
 7 echo "option numbers: \$#  $#"
 8 echo "last return:    \$?  $?"
 9 echo "all parameters: \$*  $*"
10 echo "all parameters: \$@  $@"
11 echo "file name:      \$0  $0"
12 echo "1st param:      \$1  $1"
13 echo "2nd param:      \$2  $2"
14 echo "3rd param:      \$3  $3"
15 echo "4th param:      \$4  $4"
16 echo "9th parem:      \$9  $9"
17 echo "-----------------------"
18 
19 index=1
20 
21 echo "get args by \"\$@\":"
22 
23 for arg in "$@"
24 do
25 echo "Arg #$index=$arg"
26 let "index+=1"
27 done
28 
29 echo "-----------------------"
30 
31 index=1
32 
33 echo "get args by \"\$*\":"
34 
35 for arg in "$*"
36 do
37 echo "Arg #$index=$arg"
38 done
39 
40 echo "-----------------------"

输出结果:

$ sh show.sh dont "worry be" happy
----------------------
PID:            $$  12897
option numbers: $#  3
last return:    $?  0
all parameters: $*  dont worry be happy
all parameters: $@  dont worry be happy
file name:      $0  show.sh
1st param:      $1  dont
2nd param:      $2  worry be
3rd param:      $3  happy
4th param:      $4  
9th parem:      $9  
-----------------------
get args by "$@":
Arg #1=dont
Arg #2=worry be
Arg #3=happy
-----------------------
get args by "$*":
Arg #1=dont worry be happy
-----------------------

 

linux shell变量$#,$@,$0,$1,$2的含义解释

标签:

原文地址:http://www.cnblogs.com/rustfisher/p/4684596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!