shell变量简介
1 定义变量规则
- 变量名和等号之间不能有空格。
- 首个字符必须为字母(a-z,A-Z)。
- 中间不能有空格,可以使用下划线(_)。
- 不能使用标点符号。
- 不能使用bash里的关键字(可用help命令查看保留关键字)。
- 变量名不加美元符号
name=lsh
name=”lsh”
name=’lsh’
单引号和双引号还有没引号是有却别的
区别如下
2 使用变量
使用变量直接加美元符号$,就可以了
echo $lsh
echo ${lsh}
花括号加不加都可以,但是在有歧义的地方最好加上去
比如
$lshaa
${lsh}aa
建议是所有的变量都加上花括号,那就没有歧义了
3 只读变量
使用 readonly 命令可以将变量定义为只读变量,只读变量的值不能被改变。
name=lsh
readonly lsh
[root@hadoop-slave1 shell]# name=lsh
[root@hadoop-slave1 shell]# readonly name
[root@hadoop-slave1 shell]# name="lsh"
-bash: name: readonly variable
[root@hadoop-slave1 shell]# name="lsh1"
-bash: name: readonly variable
[root@hadoop-slave1 shell]#
4删除变量
unset variable_name
unset name
但是unset 不能删除只读变量
readonly_variable=”readonly”
[root@hadoop-slave1 shell]# readonly readonly_variable
[root@hadoop-slave1 shell]# readonly_variable=”i want to change this variable”
-bash: readonly_variable: readonly variable
[root@hadoop-slave1 shell]# unset readonly_variable
-bash: unset: readonly_variable: cannot unset: readonly variable
变量类型
运行shell时,会同时存在三种变量:
- 局部变量 局部变量在脚本或命令中定义,仅在当前shell实例中有效,其他shell启动的程序不能访问局部变量。
- 环境变量 所有的程序,包括shell启动的程序,都能访问环境变量,有些程序需要环境变量来保证其正常运行。必要的时候shell脚本也可以定义环境变量。
- shell变量 shell变量是由shell程序设置的特殊变量。shell变量中有一部分是环境变量,有一部分是局部变量,这些变量保证了shell的正常运行
参考文章
http://blog.csdn.net/chinalinuxzend/article/details/1826623
http://www.runoob.com/linux/linux-shell-variable.html