0

従来のif関数とは少し書き方が違うif関数を自作しようとしています。

これは私が現在持っているものです(おそらく完成にはほど遠いです)

function check
{
    if [ "$2" = "=" ]; then
        if [ "$1" = "$3" ]; then
            // Don't know what to put in here
        elif [ "$1" != "$3" ]; then
            // Don't know what to put in here
        fi
    elif [ "$2" = "!=" ]; then
        if [ "$1" != "$3" ]; then
            // Don't know what to put in here
        elif [ "$1" = "$3" ]; then
            // Don't know what to put in here   
        fi
    fi
}

完了すると、次のように実行されます。

check $foo != 2
    //do this
end

どうすればこれを達成できますか?

インデントされたコードを組み込むにはどうすればよいですか? そして、「終了」ステートメントをどのように組み込むのですか?

4

2 に答える 2

1

あなたがやろうとしていることは、それ自体ではなく、testakaを置き換えることでうまくいくようです。関数を完成させる方法は次のとおりです。[if

function check
{
    if [ "$2" = "=" ]; then
        if [ "$1" = "$3" ]; then
            return 0
        else 
            return 1
        fi
    elif [ "$2" = "!=" ]; then
        if [ "$1" != "$3" ]; then
            return 0
        else
            return 1
        fi
    fi
    echo "Unknown operator: $2" >&2
    return 1
}

そして、これを使用する方法は次のとおりです。

if check "foo" != "bar"
then
    echo "it works"
fi
于 2013-11-11T20:08:06.437 に答える
0

のラッパーを bash で作成することに成功することはありませんif。これifは、シェルのキーワードであるためです。

キーワードは、予約、トークン、または演算子です。キーワードはシェルにとって特別な意味を持ち、実際にシェルの構文の構成要素です。例として、ifforwhile、 do 、および! がキーワードです。builtinと同様に、キーワードは Bash にハードコーディングされていますが、 builtinとは異なり、 キーワード自体はコマンドではなく、コマンド コンストラクトのサブユニットです

ここにデモンストレーションがあります:

$ type if
if is a shell keyword
$ function if { echo "something"; }
$ type if
if is a shell keyword
$ #so, 'if' has remained a shell keyword
$ #and the new created function 'if' will never work :(
$ type cd
cd is a shell builtin
$ function cd { echo "something"; }
$ type cd
cd is a function
cd () 
{ 
    echo "something"
}
$ cd $HOME
something
$ #so, 'cd' is not anymore a builtin and the new created function 'cd' works! :)
于 2013-11-11T19:25:12.257 に答える