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 " "$$"
printf "The complete list $! is %s " "$!"
printf "The complete list $- is %s " "$-"
printf "The complete list $? is %s " "$?"
printf "The complete list $* is %s " "$*"
printf "The complete list $@ is %s " "$@"
printf "The complete list $# is %s " "$#"
printf "The complete list $ is %s " "$0"
printf "The complete list $1 is %s " "$1"
printf "The complete list $2 is %s " "$2"
printf "The complete list $0,$1,$2,$3,$4 is %s " "$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

原文地址:https://www.cnblogs.com/haochuang/p/6739593.html