Monday, August 12, 2013

bash 笔记(一)——变量

1.变量的定义

varname=value
注意:等号两边不能有空格。如果变量(value)超过一个单词,则必须用引号引起。


2.变量和引号

$ fred='Four spaces between these    words.'
$ echo $fred 

Four spaces between these words. 
当使用不带双引号使用变量时,shell会把字符串切分成多个单词,在处理命令行参数时通常就这样做。如果用双引号引起,则shell把整个字符串作为一个单词处理。
$ echo "$fred"
Four spaces between these    words.
双引号和单引号的区别
双引号称为“弱引用”,单引号称为“强引用”。顾名思义,双引号会对引号里的内容进行转意,比如将变量里的内容引出;而单引号则完全拷贝单引号里的内容,对特殊字符不做转意处理。以上面$fred为例:
$ echo '$fred'
$fred

3.位置参数变量

3.1 $0, $1, $2, $3, ...

$1, $2, $3, ... 分别代表命令行中/函数第1, 2, 3, ...个参数。$0 是脚本名字。在函数中$0仍然是脚本名,而不是函数名(如果脚本是用 source 命令执行,则 $0=bash)

3.2 $* 和 $@


  • $* 把所有的参数作为一个单独的字符串,其中用环境变量IFS(internal field separator)中的第一个字符作为参数之间的分隔符。
  • $@ 等价于"$1" "$2" "$3"... "$N" ,就是N个独立的用双引号引起的字符串,它们之间用空格分开。


4.变量名通用写法

完整的变量名书写格式是${varname} 。比如你有超过9个以上的参数,你必须用${10}而不是$10 来引用第10个参数。另外当你想在输出的变量后跟一下划线,你必须用:
echo ${UID}_ 
如果使用 
echo $UID_ ,shell 会把UID_ 看作变量名。

5.变量的类型

用内建命令declare 定义变量的类型,比如 declare -i varname ,表示varname 是个整数变量。 用'-'定义,用'+'取消。常用的设置变量属性的 declare option 见下表。

Option Meaning
-a to make NAMEs indexed arrays (if supported)
-A to make NAMEs associative arrays (if supported)
-i to make NAMEs have the `integer' attribute
-l to convert NAMEs to lower case on assignment
-r to make NAMEs readonly
-t to make NAMEs have the `trace' attribute

当declare 作为命令使用时还有另外一些参数:

Option Meaning
-f restrict action or display to function names and definitions
-F restrict display to function names only (plus line number and source file when debugging)
-g create global variables when used in a shell function; otherwise ignored
-p display the attributes and value of each NAME

No comments:

Search This Blog