显示变量:echo $MAIL或者 echo ${MAIL}
[CJP@CJP ~]$ echo $MAIL
/var/spool/mail/CJP
[CJP@CJP ~]$ echo ${MAIL}
/var/spool/mail/CJP
设置变量:用等号(=)赋值就可以,可以实现设置以及修改
[CJP@CJP ~]$ myname=CJP
[CJP@CJP ~]$ echo $myname
CJP
[CJP@CJP ~]$ myname=CJP2
[CJP@CJP ~]$ echo $myname
CJP2
变量设置的一些规则:
- a、等号两边不能直接接空格,如 myname = CJP,会出现
[CJP@CJP ~]$ myname = CJP
bash: myname: command not found
[CJP@CJP ~]$ myname=CJP CJP2
bash: CJP2: command not found
- b、变量名称只能是英文和数字,但是开头字符不能是数字
[CJP@CJP ~]$ 2myname=CJP
bash: 2myname=CJP: command not found
- c、变量内容如果有空格,可以使用双引号或者单引号将内容结合起来
双引号内特殊字符如$,可以保持原有的特性
[CJP@CJP ~]$ var="language is $LANG"
[CJP@CJP ~]$ echo $var
language is zh_CN.utf8
变量内容存在单引号的时候,用双引号
[CJP@CJP ~]$ name=CJP's name
>
> ^C
[CJP@CJP ~]$ name='CJP's name'
> ^C
[CJP@CJP ~]$ name="CJP's name"
[CJP@CJP ~]$ echo $name
CJP's name
单引号内特殊字符是纯文本
[CJP@CJP ~]$ var='language is $LANG'
[CJP@CJP ~]$ echo $var
language is $LANG
- d、可用转意字符“\”将特殊字符([ENTER],$,\,!,空格等)变成一般字符
[CJP@CJP ~]$ var=\$
[CJP@CJP ~]$ echo $var
$
[CJP@CJP ~]$ name=CJP\'s\ name
[CJP@CJP ~]$ echo $name
CJP's name
- e、当一串命令中需要得到其他命令提供的信息,可以使用反单引`command`或者$(command)
[CJP@CJP ~]$ path=`echo $PATH`
[CJP@CJP ~]$ echo $path
/home/CJP/qtsdk-2010.05/qt/bin:/usr/lib/qt-3.3/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/CJP/bin
[CJP@CJP ~]$ path=$(echo $PATH)
[CJP@CJP ~]$ echo $path
/home/CJP/qtsdk-2010.05/qt/bin:/usr/lib/qt-3.3/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/CJP/bin
[CJP@CJP ~]$ version=$(uname -r)
[CJP@CJP ~]$ echo $version
2.6.32-220.el6.i686
进入目前内核的模块目录
[CJP@CJP ~]$ cd /lib/modules/$(uname -r)/kernel
[CJP@CJP kernel]$
或者
[CJP@CJP ~]$ cd /lib/modules/`uname -r`/kernel
[CJP@CJP kernel]$
- f、为了增加变量内容,可用 “$var” 或者 ${var}累加内容
[CJP@CJP ~]$ var=C
[CJP@CJP ~]$ var="$var"JP
[CJP@CJP ~]$ echo $var
CJP
[CJP@CJP ~]$ var=${var}cjp
[CJP@CJP ~]$ echo $var
CJPcjp
- g、变量如果要在其他子进程中执行,需要通过export使变量变成环境变量
[CJP@CJP ~]$ name=CJP
[CJP@CJP ~]$ bash ==进入子进程
[CJP@CJP ~]$ echo $name
==没有变量内容
[CJP@CJP ~]$ exit ==离开子进程
exit
[CJP@CJP ~]$ export name ==设置环境变量
[CJP@CJP ~]$ bash
[CJP@CJP ~]$ echo $name
CJP
[CJP@CJP ~]$ exit
exit
注:子进程(在目前的shell下打开新的shell,新的shell就是子进程)
- h、取消变量可以使用unset
[CJP@CJP ~]$ echo $var
CJPcjp
[CJP@CJP ~]$ unset var
[CJP@CJP ~]$ echo $var
[CJP@CJP ~]$