上一讲咱们介绍过系统变量和系统自定义变量,本章讲解用户自定义变量。shell
变量命名和文件命名要有描述性,少用缩写,不要使用相似a="a"无心义变量名称,根据名称能够大体知道变量含义。例如编程
STUDENTNAME="tom" #所有大写 StudentName="tom" #单词首字母大写,骆驼(camel)命名法 studentName="bill"#第二个单词字母大写,匈牙利命名法 studentname="green"#所有小写 student_name="green"#下划线区分单词
变量能够使用单引号双引号和无引号三种,单引号表示原样输出。双引号先解析语句内命令/变量和转义符等,完毕后输出,无引号通常输出简单字符串,不包含空格,复杂字符串推荐使用双引号。vim
[root@promote ~]# CHARS='example text' [root@promote ~]# echo $CHARS example text [root@promote ~]# echo '$CHARS' $CHARS [root@promote ~]# echo "$CHARS" example text [root@promote ~]#
引用命令能够使用$(command),例如$(ls)。bash
[root@promote ~]# pwd1=$(ls) [root@promote ~]# pwd /root [root@promote ~]# echo $pwd1 anaconda-ks.cfg [root@promote ~]#
$0变量比较特殊,相似还有${n}、$#、$*和$@等,注意观察,这些变量不符合通常变量命名规则,是特殊变量,称为位置参数变量。下面举例说明${n}用法.net
$演示使用${n}方法,n是>0整数 #建立文件 [root@promote ~]# echo 'echo $1' >>test.sh [root@promote ~]# ls anaconda-ks.cfg test.sh #打印第一个参数 [root@promote ~]# sh test.sh tom tom #截取第二个之后参数 [root@promote ~]# sh test.sh tom bill tom #''做为一个总体 [root@promote ~]# sh test.sh 'tom bill' tom bill #""做为一个总体 [root@promote ~]# sh test.sh "tom bill" tom bill [root@promote ~]# [root@promote ~]# echo 'echo $1 $2' >> test.sh [root@promote ~]# cat test.sh echo $1 $2 [root@promote ~]# vim test.sh [root@promote ~]# sh test.sh tom bill tom bill [root@promote ~]# sh test.sh tom tom [root@promote ~]# sh test.sh tom green tom green [root@promote ~]# sh test.sh 'john carry' tom green john carry tom [root@promote ~]# sh test.sh "john carry" tom green john carry tom [root@promote ~]# #推荐使用,大于10不使用{}致使输出异常 [root@promote ~]# echo 'echo ${1} ${2}' >> test.sh [root@promote ~]# sh test.sh tom #
再看$0使用方法须要和${0}加以区别。code
[root@promote ~]# echo 'echo $0' >>echoA.sh [root@promote ~]# ls anaconda-ks.cfg echoA.sh [root@promote ~]# sh echoA.sh echoA.sh [root@promote ~]# sh /root/echoA.sh /root/echoA.sh [root@promote ~]# dirname /root/echoA.sh /root [root@promote ~]# echo 'echo ${0}' >>echoA.sh [root@promote ~]# sh echoA.sh echoA.sh echoA.sh [root@promote ~]# dirname /root/echoA.sh /root [root@promote ~]# dirname /root/echoA.sh /root [root@promote ~]# #@获取脚本后参数总数
$?、$$、$!和$_表示状态变量。进程
$?经常使用,表示上一个命令返回状态码,0表示成功,其余表示失败,本例为成功$$获取当前shell解释器进程PID,$!获取上一个shell解释器进程PID [root@promote ~]# rm -f test.sh [root@promote ~]# echo '#!/bin/sh > echo "number:$#" > echo "filename:$0" > echo "first :$1" > echo "second:$2" > echo "argume:$@" > echo "show parm list:$*" > echo "show process id:$$" > echo "show precomm stat: $?"' >>test.sh [root@promote ~]# sh test.sh number:0 filename:test.sh first : second: argume: show parm list: show process id:20914 show precomm stat: 0 [root@promote ~]# #转载自跟老男孩学Linux Shell编程实战 P50 [root@promote ~]# echo '#!/bin/bash > echo $$ >>/tmp/test.pid > sleep 60 '>>testpid.sh [root@promote ~]# cat testpid.sh #!/bin/bash echo $$ >>/tmp/test.pid sleep 60 [root@promote ~]# ps -ef | grep testpid | grep -v grep root 21239 17415 0 18:57 pts/0 00:00:00 bash testpid.sh #&表示后台执行 [root@promote ~]# bash testpid.sh & [4] 21300 [root@promote ~]#