Bash字符串处理(与Java对照) - 1.(字符串)变量声明(二)

2014-11-24 02:40:30 · 作者: · 浏览: 4
fix,
separated by the first character of the IFS special variable.

[root@jfht ~]# echo ${!VAR}

[root@jfht ~]# VAR=
[root@jfht ~]# echo ${!VAR}

[root@jfht ~]# echo ${!VAR*}
VAR
[root@jfht ~]# VAR1=
[root@jfht ~]# echo ${!VAR*}
VAR VAR1
[root@jfht ~]#

将变量声明为只读
格式:readonly VAR=STRING
help readonly 写道
readonly: readonly [-af] [name[=value] ...] or readonly -p
The given NAMEs are marked readonly and the values of these NAMEs may
not be changed by subsequent assignment. If the -f option is given,
then functions corresponding to the NAMEs are so marked. If no
arguments are given, or if `-p' is given, a list of all readonly names
is printed. The `-a' option means to treat each NAME as
an array variable. An argument of `--' disables further option
processing.

格式:declare -r VAR=STRING
help declare 写道
-r to make NAMEs readonly

取消变量、删除变量
格式:unset VAR

[root@jfht ~]# VAR=STRING
[root@jfht ~]# echo "$VAR"
STRING
[root@jfht ~]# unset VAR
[root@jfht ~]# echo "$VAR"

[root@jfht ~]#

定义局部变量
在默认情况下,变量都是全局变量。在前面加上local或者declare之后就变成了局部变量。
格式:local VAR
格式:local VAR=STRING
格式:declare VAR
格式:declare VAR=STRING
局部变量在函数中使用,如下所示
myfunc() {
GGG=Global
# GGG变量是全局变量
local STR=Hello
# STR变量的有效范围只在myfunc函数内
declare VAR=World
# VAR变量也是局部变量
}


[root@smsgw root]# myfunc(){
> GGG=Global
> local STR=Hello
> declare VAR=World
> }
[root@smsgw root]# GGG=YesGlobal
[root@smsgw root]# STR=NotHello
[root@smsgw root]# VAR=NotWorld
[root@smsgw root]# myfunc
[root@smsgw root]# echo $GGG $STR $VAR
Global NotHello NotWorld
[root@smsgw root]#

作者“Bash @ Linux