如何制作嵌套的 ifs

如何制作嵌套的 ifs

我正在尝试使用脚本创建自己的命令,但我对在另一个脚本中创建 if 的正确方法有点怀疑。下面的代码显示了我如何尝试做到这一点,但我想这是不对的。

#!/bin/bash

if test -z $1
then
    echo "Wrong usage of command, to check proper wars user -h for help."
    exit
else
    if test "$1"="-h"
    then
        echo "OPTIONS:  -h (help), -a (access point MAC), -c (current target[s] MAC[s])
"
        exit
    fi

    if test "$1"="-c"
    then
        echo "Usage error, access point MAC comes first."
        exit
    fi
fi

答案1

您的嵌套if语句看起来大部分都很好,您的测试可能是导致脚本“不起作用”的原因。

我已将您的tests 更改为 bash[[扩展测试命令。

另外,if我认为它应该作为单个if elif.

#!/bin/bash

if [[ -z "$1" ]]
then
    echo "Wrong usage of command, to check proper wars user -h for help."
    exit
else
    if [[ "$1" == "-h" ]]
    then
        echo -e "OPTIONS:  -h (help), -a (access point MAC), -c (current target[s] MAC[s])\n"
        exit
    elif [[ "$1" == "-c" ]]
    then
        echo "Usage error, access point MAC comes first."
        exit
    fi
fi

您的测试应该在 和 测试字符串之间有一个空格,但我认为如果您要在 bash 中编写脚本,$1最好使用 bash测试。[[以下是test内置函数如何工作的一些示例:

$ test true && echo yes || echo no
yes
$ test false && echo yes || echo no
yes
$ test true=false && echo yes || echo no
yes
$ test true = false && echo yes || echo no
no

此外,在这种情况下,我认为if根本不需要您的嵌套条件。您可以将其简化为:

#!/bin/bash

if [[ "$1" == "-h" ]]; then
    echo -e "OPTIONS:  -h (help), -a (access point MAC), -c (current target[s] MAC[s])\n"
    exit
elif [[ "$1" == "-c" ]]; then
    echo "Usage error, access point MAC comes first."
    exit
else
    echo "Wrong usage of command, to check proper wars user -h for help."
    exit
fi

相关内容