您的位置:首页 > 运维架构 > Shell

bash笔记之变量,引用,测试

2010-11-24 20:32 253 查看
变量

可以把命令赋值给变量 注意=后面的是"`"(反引号)例如

a=`ls -l` # Assigns result of 'ls -l' command to 'a'
echo $a # Unquoted, however, it removes tabs and newlines.
echo
echo "$a" # The quoted variable preserves whitespace.


或者使用$()的形式 也是可以的 例如

R=$(cat /etc/redhat-release)
arch=$(uname -m)


bash变量是untype的 根据不同的环境 会适应的做一些转化的地方

关于positional 变量 $0代表的是文件名 $1 $2 ...指的是文件名后的参数
bash$ ./test.sh 1 2 3
$0 是./test.sh
$1 是1
$2 是2
$3 是3
$# 是参数的个数  此刻为3


对positional变量还可以采用间接引用

args=$# # Number of args passed.
lastarg=${!args}
# 或者写成
lastarg=${!#}
# 但是下面是错误的
# lastarg=${!$#}


另外shift可以对positional变量进行重新赋值,形如

$1 <--- $2, $2 <--- $3, $3 <--- $4, etc.

此时原来的$1没有了 变成了$2的值 最后一个$4的值消失了参数个数也变为原来的个数减1

还可以在shift后加参数,指定一次移动的个数 但是假如指定的参数小于实际的个数,就会出现错误

until [ -z "$1" ] # Until all parameters used up . . .
do
echo -n "$1 "
shift
done


until [ -z "$1" ]
do
echo -n "$1 "
shift 5   #  If less than 5 pos params,
done      #+ then loop never ends!


引用

双引用可以防止字符串分割,在双引号里所有的字符看做是一个整体

List="one two three"
for a in $List # Splits the variable in parts at whitespace.
do
echo "$a"
done
# one
# two
# three

for a in "$List" # Preserves whitespace in a single variable.
do # ^ ^
echo "$a"
done
# one two three


测试

测试命令有test,[], [[...]], ((...))

其中test和[]是一致的,测试表达式的值,如果为真,则返回0(success),反之,返回1。

经测试所有单个数字值和字符串都返回0,而null和未申明变量返回1。
[[...]] 是test的扩展,可以容纳逻辑符号<、>、$$、||

((...))测试一个算术结果,如果值为0,返回1;反之,返回0

(( 0 ))
echo "Exit status of /"(( 0 ))/" is $?." # 1
(( 1 ))
echo "Exit status of /"(( 1 ))/" is $?." # 0
(( 5 > 4 )) # true
echo "Exit status of /"(( 5 > 4 ))/" is $?." # 0
(( 5 > 9 )) # false
echo "Exit status of /"(( 5 > 9 ))/" is $?." # 1


附:

文件测试操作符:

-e file exists
-a file exists
This is identical in effect to -e. It has been "deprecated," [30] and its use is discouraged.

-f file is a regular file (not a directory or device file)
-s file is not zero size
-d file is a directory
-b file is a block device
-c file is a character device

-p file is a pipe
-h file is a symbolic link
-L file is a symbolic link
-S file is a socket
-t file (descriptor) is associated with a terminal device
This test option may be used to check whether the stdin [ -t 0 ] or stdout [ -t 1 ] in a given script is a terminal.
-r file has read permission (for the user running the test)
-w file has write permission (for the user running the test)
-x file has execute permission (for the user running the test)

f1 -nt f2 file f1 is newer than f2
f1 -ot f2 file f1 is older than f2
f1 -ef f2 files f1 and f2 are hard links to the same file
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: