在定义了此功能的脚本中:
#!/bin/bash --
outtrue (){ printf "%15s is T|%s" "$*" "$?"; }
outfalse (){ printf "%15s is F|%s" "$*" "$?"; }
tval1(){ [ "$@" ] && outtrue "$@" || outfalse "$@"; }
tval2(){ [ "$*" ] && outtrue "$@" || outfalse "$@"; }
tval3(){ [[ "$@" ]] && outtrue "$@" || outfalse "$@"; }
tval(){
printf "test %s\t" "$1"; shift
case $1 in
(1) shift; tval1 "$@" ;;
(2) shift; tval2 "$@" ;;
(3) shift; tval3 "$@" ;;
esac
printf "\n"
}
此测试工作完美(如预期):
xyz="str"; tval "-n var" 1 "-n" "$xyz"
xyz="str"; tval "-z var" 1 "-z" "$xyz"
one=1; tval "1 -eq \$one" 1 "1" "-eq" "$one"
one=2; tval "1 -eq \$one" 1 "1" "-eq" "$one"
结果:
test -n var -n str is T|0
test -z var -z str is F|1
test 1 -eq $one 1 -eq 1 is T|0
test 1 -eq $one 1 -eq 2 is F|1
然而,改变" $ @"到" $ *"或使用bash测试[[...]]
制作
测试失败(请注意,此处使用了函数2或3):
one=1; tval "1 -eq \$one" 2 "1" "-eq" "$one"
one=2; tval "1 -eq \$one" 2 "1" "-eq" "$one"
one=1; tval "1 -eq \$one" 3 "1" "-eq" "$one"
one=2; tval "1 -eq \$one" 3 "1" "-eq" "$one"
结果:
test 1 -eq $one 1 -eq 1 is T|0
test 1 -eq $one 1 -eq 2 is T|0
test 1 -eq $one 1 -eq 1 is T|0
test 1 -eq $one 1 -eq 2 is T|0
你看到了什么问题吗?
答案 0 :(得分:1)
报价!!
使用“$ *”和bash [[...]]
命令行值不会被拆分。
如果单词不为空,则测试等同于[ word ]
,因此为真。