ネストされたifを作成する方法[閉じる]

ネストされたifを作成する方法[閉じる]

スクリプトを使用して独自のコマンドを生成しようとしていますが、他のスクリプトで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ステートメントはほとんど問題ないようですが、テストがスクリプトが「機能しない」原因になる可能性があります。

testあなたのsを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でスクリプトを作成する場合は$1bashテストを使用する方が良いと思います。組み込み関数の仕組みのいくつかの例[[は次のとおりです。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

おすすめ記事