2009年6月29日星期一

Bash 变量长度

BASH: $#---所有参数
readonly--修饰常量#

使用数组
[bob in ~] ARRAY=(one two three)

[bob in ~] echo ${ARRAY[*]}
one two three

[bob in ~] echo $ARRAY[*]
one[*]

[bob in ~] echo ${ARRAY[2]}
three

[bob in ~] ARRAY[3]=four

[bob in ~] echo ${ARRAY[*]}
one two three four

变量的长度
[bob in ~] echo $SHELL
/bin/bash

[bob in ~] echo ${#SHELL}
9

[bob in ~] ARRAY=(one two three)

[bob in ~] echo ${#ARRAY}
3

#####################################################
以下的例子显示了一个简单的测试:

anny ~> if [ $? -eq 0 ]
More input> then echo 'That was a good job!'
More input> fi
That was a good job!

anny ~>


一个通过比较字符串来测试用户ID的例子:

if [ "$(whoami)" != 'root' ]; then
echo "You have no permission to run $0 as non-root user."
exit 1;
fi

使用Bash,你可以缩短这样的结构。下面是以上测试的精简结构:

[ "$(whoami)" != 'root' ] && ( echo you are using a non-privileged account; exit 1 )


类似于如果测试为真就执行的 “&&” 表达式, “||” 指定了测试为假就执行。类似于 “&&” 表达式指明了在两个测试条件为真时所采取的动作,“||” 指明测试为假时所采取的行动。