5. 变量(Variables)

来源:互联网 发布:淘宝手机助手安卓版 编辑:程序博客网 时间:2024/06/05 23:59

我们可以在Shell中定义变量,在第4节中,我们创建第一的练习的脚本

 #!/bin/bash # #copy /var/log/messages to /var/log/messages.old #then delete the content of the /var/log/messages.oldcp /var/log/messages /var/log/messages.oldcat /dev/null > /var/log/messages.oldecho log file copied and cleaned upexit 0

现在在这个脚本的基础上稍作修改,用变量的方式来定义文件名

 #!/bin/bash # #copy /var/log/messages to /var/log/messages.old #then delete the content of the /var/log/messages.old #Usage: ./clearlogsLOGFILE = /var/log/messagescp $LOGFILE  $LOGFILE.oldcat /dev/null > $LOGFILE.oldecho log file copied and cleaned upexit 0

我们用 LOGFILE = /var/log/messages 来定义变量,其中LOGFILE是变量名,/var/log/messages是变量的值

我们用$LOGFILE来引用变量值

shell的变量还是比较简单的,不过介绍一个重要的概念。
就是shell脚本的作用域,http://blog.csdn.net/bailyzheng/article/details/7488769这篇博客中介绍的已经很清楚,我就直接引用过来了。

shell与export命令
用户登录到Linux系统后,系统将启动一个用户shell。在这个shell中,可以使用shell命令或声明变量,也可以创建并运行
shell脚本程序。运行shell脚本程序时,系统将创建一个子shell。此时,系统中将有两个shell,一个是登录时系统启动的shell,另一
个是系统为运行脚本程序创建的shell。当一个脚本程序运行完毕,它的脚本shell将终止,可以返回到执行该脚本之前的shell。从这种意义上来
说,用户可以有许多 shell,每个shell都是由某个shell(称为父shell)派生的。 在子
shell中定义的变量只在该子shell内有效。如果在一个shell脚本程序中定义了一个变量,当该脚本程序运行时,这个定义的变量只是该脚本程序内
的一个局部变量,其他的shell不能引用它,要使某个变量的值可以在其他shell中被改变,可以使用export命令对已定义的变量进行输出。
export命令将使系统在创建每一个新的shell时定义这个变量的一个拷贝。这个过程称之为变量输出。

还是用实例来解释:

[root@localhost ~]# COLOR=red[root@localhost ~]# echo $COLORred[root@localhost ~]# bash[root@localhost ~]# echo $COLOR[root@localhost ~]# exitexit[root@localhost ~]# echo $COLORred[root@localhost ~]# 

bash命令是打开一个subshell,可以看到在subshell中,parentshell中的变量是访问不到的。

[root@localhost ~]# export COLOR=red[root@localhost ~]# echo $COLORred[root@localhost ~]# bash[root@localhost ~]# echo $COLORred[root@localhost ~]# 

我们用export 来让COLOR变量能被subshell也访问到。

所以我们在Linux设置系统环境变量的时候,经常会用到export语句。这回大家明白是怎么回事了吧。