Bash関数が見つからないコマンドを返す場合

Bash関数が見つからないコマンドを返す場合

これを行う関数を作成しようとしています。

$ test-function -u {local-path} {destination}

最初の引数がある場合は、-u次の2つの引数をアップロード/コピー/再同期するファイルのパスとターゲットとして使用する関数を実行します。

$ test-function -d {local-path} {destination}

最初の引数が-u(または-d)の場合は、次の2つの引数をダウンロード/コピー/再同期するファイルのパス(現在のフォルダにあると仮定)とターゲットとして使用する関数を実行します。

解決策を提案する答えを見つけました。ここそしてここ。しかし、私の関数は.bash_profile次のエラーを返します。

function test_func {
    local a="$1"
    local a="$2"

    if ( a == "-u" ); then
        echo "This means upload"
    else
        echo "This means download"
    fi
}

alias test-function="test_func"

それから:

$ test-function -u
-bash: a: command not found
This means download
$ test-function -d
-bash: a: command not found
This means download

コードを次のように変更した場合:

if [[a == "-u"]]; then
...

時には次のように進行します。

$ test-function -u
-bash: [[a: command not found
This means download

私が見つけた答えの1つに基づいてコードを変更した場合:

if ((a == "-u")); then
...

時には次のように進行します。

line 53: syntax error near unexpected token `}'

このエラーはdoubleに関連しているようです((...))。どうすればいいですか?

ベストアンサー1

エラーは次のとおりです。

if ( a == "-u" ); then
    echo "This means upload"
else
    echo "This means download"
fi

構成ifにはtrueまたはfalseと評価される式が必要です。たとえば、コマンド(if ls; then echo yes;fi)またはテスト構造です。テスト構成を使用しようとしていますが、テスト演算子()を使用する代わりに[括弧を使用してください。

括弧はサブシェルを開きます。したがって、この表現は「引数を使用してサブシェルでコマンドを実行します。( a == "-u" )必要なものは次のとおりです。a=="-u"

if [ "$a" = "-u" ]; then  ## you also need the $ here
    echo "This means upload"
else
    echo "This means download"
fi

[[ ]]またはで動作する移植不能な設定を使用するには、末尾のbashスペースを追加する必要があります[[

if [[ "$a" == "-u" ]]; then
    echo "This means upload"
else
    echo "This means download"
fi

if [[a == "-u" ]]シェルを[[a単一のコマンドで読み取ろうとしましたが失敗しました。

最後に、この(( ))構造は移植性がありませんが、算術評価のためにbash(および他のいくつかのシェル)で動作します。からman bash

  ((expression))
          The  expression is evaluated according to the rules described below under
          ARITHMETIC EVALUATION.  If the value of the expression is  non-zero,  the
          return  status  is  0; otherwise the return status is 1.  This is exactly
          equivalent to let "expression".

したがって、この場合は使用したいものではありません。これらすべてをまとめると、次のようなものが欲しい。

function test_func {
    local a="$1"

    if [ "$a" = "-u" ]; then
        echo "This means upload"
    else
        echo "This means download"
    fi
}

alias test-function="test_func"

おすすめ記事