• 本页内容

35. 用 [[ ]] 扩展测试命令


我们已经知道,[ ]是测试命令,通常与if语句一起使用。 [[ ]]是扩展测试命令,是[ ]命令的高级变体,可以执行 [ ]执行的所有操作,此外还执行以下操作:

  • 当您使用===!=时,使用字符串比较中的模式匹配
  • =~ 位于扩展测试命令内
  • &&|| 在扩展测试命令中
  • <> 用于在扩展测试命令中进行比较
  • 将表达式括在( )中以更改其计算优先级
  • ~ 波形符扩展、算术扩展和参数扩展
  • 命令替换和进程替换

以下示例演示如何使用扩展测试命令来使用模式匹配(使用=||=~)。

$ cat extended-test1.sh
name=${1}

# 1. You can use pattern matching in [[ ]]
if [ $name = bon* ]; then
    echo "[test] command: Good Morning, Mr. Bond"
fi
if [[ $name = bon* ]]; then
    echo "[[test]] command: Good Morning, Mr. Bond"
fi

# 2. You can use || && inside [[ ]]
if [[ $name = super || $name = bon* ]]; then
    echo "[[test]] command: Good Morning, Mr. Hero"
fi

# 3. You can use =~ for regular expression inside [[ ]]
if [[ $name =~ ^b ]]; then
    echo "[[test]] command: Mr. $name, your name starts with 'b'"
fi

$ ./extended-test1.sh bon
[[test]] command: Good Morning, Mr. Bond
[[test]] command: Good Morning, Mr. Hero
[[test]] command: Mr. bon, your name starts with 'b'

以下示例演示如何使用扩展测试命令来使用模式匹配(使用=)和正则表达式比较(使用=~)。

$ cat extended-test2.sh
i=1

cd ~
for item in *
do
    if [[ $item = *.jpg ]]; then
        echo "Image $((i++)) : $item"
    fi
done

cd /etc
for item in *.conf
do
    if [[ $item =~ ^a ]]; then
        echo "Conf $((i++)) : $item"
    fi
done

$ ./extended-test2.sh
Conf 1 : asound.conf
Conf 2 : autofs_ldap_auth.conf