Fork me on GitHub

Linux shell中一些参数与变量简介

linux中shell变量$#,$@,$0,$1,$2,$!,$$,$*,$-,$@......等很多个,很容易记错,这里再次整理一下,相关含义解释如下,并附上一个实践截图。

多看几次,多用几次,应该就记熟悉了。

 
变量说明: 
$$ 
Shell本身的PID(ProcessID) 
$! 
Shell最后运行的后台Process的PID 
$? 
最后运行的命令的结束代码(返回值) 
$- 
使用Set命令设定的Flag一览 
$* 
所有参数列表。如"$*"用「"」括起来的情况、以"$1 $2 … $n"的形式输出所有参数。 
$@ 
所有参数列表。如"$@"用「"」括起来的情况、以"$1" "$2" … "$n" 的形式输出所有参数。 
$# 
添加到Shell的参数个数 
$0 
Shell本身的文件名 
$1~$n 
添加到Shell的各参数值。$1是第1参数、$2是第2参数…。 

 

根据上面的解释,我做了一下实验,如下:

#!/bin/bash


printf "The complete list \$\$ is %s\n" "$$"
printf "The complete list \$\! is %s\n" "$!"
printf "The complete list \$\- is %s\n" "$-"
printf "The complete list \$\? is %s\n" "$?"
printf "The complete list \$\* is %s\n" "$*"
printf "The complete list \$\@ is %s\n" "$@"
printf "The complete list \$\# is %s\n" "$#"
printf "The complete list \$\0 is %s\n" "$0"
printf "The complete list \$\1 is %s\n" "$1"
printf "The complete list \$\2 is %s\n" "$2"
printf "The complete list \$0,\$1,\$2,\$3,\$4 is %s\n" "$0,$1,$2,$3,$4"

shell执行结果如下:

对着再看几次,应该就记住了。

 

也就是说:

$# 是传给脚本的参数个数
$0 是脚本本身的名字
$1是传递给该shell脚本的第一个参数
$2是传递给该shell脚本的第二个参数
$@ 是传给脚本的所有参数的列表

 

 

知识库:http://lib.csdn.net/home

可以参考这本在线的电子书:http://www.tldp.org/LDP/abs/abs-guide.pdf

posted @ 2017-04-20 16:46  念槐聚  阅读(553)  评论(0编辑  收藏  举报

IT技术&应用开发&研究 - 创建于 2008年05月12日

这是一位IT工程师的个人站,内容主要是网站开发方面的技术文章,大部分来自学习或工作,部分来源于网络,希望对大家有所帮助。

致力于软件学习&研究工作,涉及Linux与软件开发出、测试、产品、行业相关知识,关注互联网前沿技术与与创业趋势等。


博客园 | Github | W3C

返回顶部