➜ time (for m in {1..100000}; do test -d .; done;)( for m in {1..100000}; do; test -d .; done; ) 0.21s user 0.15s system 98% cpu 0.366 total➜ time (for m in {1..100000}; do [ -d . ]; done;)( for m in {1..100000}; do; [ -d . ]; done; ) 0.23s user 0.15s system 98% cpu 0.388 total➜ time (for m in {1..100000}; do [[ -d . ]]; done;)( for m in {1..100000}; do; [[ -d . ]]; done; ) 0.07s user 0.07s system 97% cpu 0.141 total➜ time (for m in {1..1000000}; do test -d .; done;)( for m in {1..1000000}; do; test -d .; done; ) 2.24s user 1.51s system 95% cpu 3.927 total➜ time (for m in {1..1000000}; do [[ -d . ]]; done;)( for m in {1..1000000}; do; [[ -d . ]]; done; ) 0.68s user 0.59s system 99% cpu 1.282 total➜ time (for m in {1..1000000}; do [[ -d . ]]; done;)( for m in {1..1000000}; do; [[ -d . ]]; done; ) 0.70s user 0.60s system 99% cpu 1.310 total➜ time (for m in {1..1000000}; do [ -d . ]; done;)( for m in {1..1000000}; do; [ -d . ]; done; ) 2.36s user 1.48s system 99% cpu 3.855 total➜ time (for m in {1..1000000}; do [ -d . ]; done;)( for m in {1..1000000}; do; [ -d . ]; done; ) 2.42s user 1.50s system 99% cpu 3.938 total➜ time seq 1012345678910seq 10 0.00s user 0.00s system 69% cpu 0.003 total
注意:[]是test的精简表达式,在[] 表达式中,常见的>,<需要加转义字符,表示字符串大小比较,以acill码 位置作为比较。 不直接支持<>运算符,还有逻辑运算符|| && 它需要用-a[and] –o[or]表示
注意:[[]] 运算符只是[]运算符的扩充。能够支持<,>符号运算不需要转义符,它还是以字符串比较大小。里面支持逻辑运算符:|| &&
bash的条件表达式中有三个几乎等效的符号和命令:test,[]和[[]]。通常,大家习惯用if [];then这样的形式。而[[]]的出现,根据ABS所说,是为了兼容><之类的运算符。比较它们性能,发现[[]]是最快的。
不考虑对低版本bash和对sh的兼容的情况下,用[[]]是兼容性强,而且性能比较快,在做条件运算时候,可以使用该运算符。