bash中[test]和[[test]]有什么区别?

时间:2013-01-20 14:13:31

标签: bash testing conditional-statements

bash中[test]和[[test]]有什么区别? 什么时候比另一个更合适?最后;做什么?

if  [[ -z $DIRECTORY ]];
then
     DIRECTORY=html
fi

if [ ! -d "$DIRECTORY" ]; then
    echo installation directory "'${DIRECTORY}'" does not exist
    exit 1
fi

3 个答案:

答案 0 :(得分:3)

[[是一个类似于[命令(但功能更强大)的bash关键字。请参阅http://mywiki.wooledge.org/BashFAQ/031http://mywiki.wooledge.org/BashGuide/TestsAndConditionals除非您是为POSIX sh撰写内容,否则我们建议使用[[

答案 1 :(得分:0)

我们通常使用单方括号:

  • 使用文件检查并希望使用模式(例如星号):if [ -L $file ]; then
  • 检查算术表达式:if [ $a -lt $b ]; then
  • 使用字符串检查内容,并希望使用" "并将特殊字符视为正常字符(例如星号):if [ -z "$string" ]; then

当我们:

时,我们通常会加上方括号
  • 想要使用带字符串的模式(例如星号):if [[ "$string1" == *[sS]tring* ]]; then
  • 文件名中的块模式(例如星号),例如我们搜索名为* .sh:if [[ -a *.sh ]]; then
  • 的文件
  • 想要使用运营商&&和||:if [[ $a == 3 || $b == 4]]; then
  • 不想在" "
  • 中添加字符串

答案 2 :(得分:0)

[适用于shell,[[适用于bash。

例如:
试试[ $A -eq 1 ]:如果未设置$A,则会引发错误 [[ $A -eq 1 ]]将有效。