command_stringでエイリアスを使用する方法は?

command_stringでエイリアスを使用する方法は?

通常、llエイリアスが次に設定された.bashrcファイルがあります。

alias ll='ls -l'

手動で呼び出すとうまくllいきます。しかし、時には文字列からコマンドを実行する必要があります。だから私は以下を実行したいと思います。

COMMAND="ll"
bash --login -c "$COMMAND"

残念ながら、これはllコマンドが見つからないと不平を言って失敗します。この範囲で実際に定義されていることを確認すると、次のようになります。

COMMAND="alias"
bash --login -c "$COMMAND"

上記はすべてのエイリアスを正しく印刷します。

bashの-c command_stringパラメータでエイリアスコマンドを使用する方法はありますか?

ベストアンサー1

ここで注意すべきいくつかの点の最初のものは、--loginオプションを使用した実行に関するものです。

When bash is invoked as an interactive login shell, or as a non-inter‐
active shell with the --login option, it first reads and executes  com‐
mands  from  the file /etc/profile, if that file exists. After reading
that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile,
in  that order, and reads and executes commands from the first one that
exists and is readable.

したがって、このコマンドはを読みません.bashrc。次に、エイリアスはインタラクティブシェルでのみ機能するため、エイリアスを取得してもコマンドでは機能しません。ただし、この関数は非対話型シェルで機能できます。したがって、エイリアスを関数に変換し、上記のいずれかにソースを指定する必要があります~/.bash_profile

あるいは、現在の環境で定義されている関数を継承した関数にエクスポートすることもできますbash -c。私はこの機能を持っています:

adrian@adrian:~$ type fn
fn is a function
fn () 
{ 
    find . -name "$1"
}

次のようにサブシェルから呼び出すことができます。

adrian@adrian:~$ export -f fn
adrian@adrian:~$ bash -c "fn foo*"
./foo.bar

おすすめ記事