代码之家  ›  专栏  ›  技术社区  ›  Demi

为什么这个shell脚本不起作用?

  •  1
  • Demi  · 技术社区  · 12 年前

    我注意到find-execdir是不可移植的,所以我决定找到一种只使用find-exec的可移植方法来实现同样的效果。要做到这一点,必须能够确定“find”找到的从“/”到目录的路径是否包含任何符号链接,如果包含,则拒绝遍历。我写了一个小脚本来确定给定的路径是否包含符号链接,但无论我给它什么,它似乎总是返回代码1。打印任何内容的命令都不会触发,除非我给它一个非目录,在这种情况下,第一个printf命令会触发。

    #!/bin/sh -e
    # If any commands fail, the script should return a nonzero status
    [ -d "$1" ] || printf "%s is not a directory" "$1" && exit 1  # Tests if argument is a directory
    cd "$1" || echo "Could not change directory" && exit 1 # If it is a directory, goes to it
    until [ "$PWD" = '/' ] # Loop until root directory reached 
    do
        cd .. || echo "Could not change directory" && exit 1 # Go to parent directory
        [ -d "$PWD" ] || printf "%s is not directory" "$PWD" && exit 1 # Check that this is a directory
    done
    echo "Given an okay directory"
    exit 0
    
    3 回复  |  直到 12 年前
        1
  •  1
  •   micromoses    12 年前

    对于每个条件行,您应该将失败包含在 () 。例如:

    [ -d "$1" ] || (printf "%s is not a directory" "$1" && exit 2)
    

    我将进一步解释@Kevin所写的内容:如果第一个语句失败( [ -d ] ),则执行第二条语句。由于第二条成功(只有在极少数情况下printf才会失败),因此执行最后一条语句。在这种格式中,只有在前两个都失败的情况下,exit语句才会被执行。如果它不是一个目录,则会得到一个printf和一个出口。如果是目录,则第一个 || 变为true,bash不需要测试下一个(printf),而是转到 && ,这也是出口。将故障封装为一体可以防止这种情况的发生。

        2
  •  1
  •   Kevin    12 年前

    在bash中(与类c语言不同) && || 具有相同的优先级。这意味着你

    command || echo error && exit 1
    

    语句被解释为

    { command || echo error } && exit 1
    

    自从 echo 即使 command 否则,第一个块将成功 exit 语句将被执行。

        3
  •  0
  •   John B    12 年前

    您可以检查 $1 不是具有反向的目录 ! -d 和使用 if; then 在返回true之后执行命令。

    #!/bin/sh -e
    # If any commands fail, the script should return a nonzero status
    if [ ! -d "$1" ]
    then
        printf "%s is not a directory" "$1"
        exit 1 # Tests if argument is a directory
    fi
    cd "$1" # If it is a directory, goes to it
    until [ "$PWD" = '/' ] # Loop until root directory reached
    do
        cd .. # Go to parent directory
    done
    echo "Given an okay directory"
    exit 0