文档介绍:深入浅出Shell编程: Shell 变量
深入浅出Shell编程: Shell 变量
1 系统变量
2 Shell用户变量
基础
使用技巧
shell 中的数组
3 shell 环境变量
先不要管Shell的版本,来看看Shell 变量,在Shell中有三种变量:系统变量,环境变量,用户变量。其中用户变量在编程过程中使用最多,系统变量在对参数判断和命令返回值判断会使用,环境变量主要是在程序运行的时候需要设置。
1 系统变量
Shell常用的系统变量并不多,但却十分有用,特别是在做一些参数检测的时候。下面是Shell常用的系统变量
表示方法
描述
$n
$1 表示第一个参数,$2 表示第二个参数...
$#
命令行参数的个数
$0
当前程序的名称
$?
前一个命令或函数的返回码
$*
以"参数1 参数2 ... " 形式保存所有参数
$@
以"参数1" "参数2" ... 形式保存所有参数
$$
本程序的(进程ID号)PID
$!
上一个命令的PID
其中使用得比较多得是$n $# $0 $? ,看看下面的例子: BeautifierPlugin Error: Unable to handle "bash" syntax.
#!/bin/sh
#This file is used to explain the shell system variable.
echo "the number of parameter is $# ";
echo "the return code of mand is $?";
echo "the script name is $0 ";
echo "the parameters are $* ";
echo "\$1 = $1 ; \$2 = $2 ";
下面是运行结果:
BeautifierPlugin Error: Unable to handle "bash" syntax.
-bash-$ ./ winter stlchina
the number of parameter is 2
the return code of mand is 0
the script name is ./
the parameters are winter stlchina
$1 = winter ; $2 = stlchina
这个例子太简单了,一点也不实用,下面来个实用的,如果你看不懂,没有关系,后面的内容会有详细解释。 BeautifierPlugin Error: Unable to handle "bash" syntax.
#!/bin/sh
if [ $# -ne 2 ] ; then
echo "Usage: $0 string file";
exit 1;
fi
grep $1 $2 ;
if [ $? -ne 0 ] ; then
echo "Not Found \"$1\" in $2";
exit 1;
fi
echo "Found \"$1\" in $2";
上面的例子中使