コマンド置換を使用するときにbashが[をテスト文字として扱わないようにするにはどうすればよいですか? [コピー]

コマンド置換を使用するときにbashが[をテスト文字として扱わないようにするにはどうすればよいですか? [コピー]

$()bashで修正されていない出力を取得する方法は?

$(command)bashにコマンド置換結果(または経由)を返すようにします`command`が、bashは開いている角かっこをtest組み込みとして処理し、テキストを評価します。

> echo "This shows an IP in brackets [127.0.0.1] when not in the command substitution context."
This shows an IP in brackets [127.0.0.1] when not in the command substitution context.

> echo $(echo "This should show an IP in brackets [127.0.0.1] but instead evaluates to '1'.")
This should show an IP in brackets 1 but instead evaluates to '1'.

> echo $(echo "The subtle addition of a space causes [127.0.0.1 ] to behave differently.")
The subtle addition of a space causes [127.0.0.1 ] to behave differently.

背景

echo上記の最小例を使用することはすべてです。最終使用には、このホストの出力が含まれているpingtracert、このホストに表示されるホストのIPが表示されます(つまり、すべてのホストエントリが尊重されます)。この使用法では、コマンドの文字列出力をほとんど制御できません。

> grep -E "^[^#].*stackoverflow" /c/Windows/System32/drivers/etc/hosts
127.0.0.1 stackoverflow.com

> tracert -h 1 -w 1 stackoverflow.com | awk '/Tracing/'
Tracing route to stackoverflow.com [127.0.0.1]

> ping -n 1 -w 1 stackoverflow.com | awk '/Pinging/'
Pinging stackoverflow.com [127.0.0.1] with 32 bytes of data:

# Using dig or nslookup would show a real IP rather than the forced IP from the hosts entry.
> dig @ns1 +nocmd stackoverflow.com +noall +answer
stackoverflow.com.      118     IN      A       151.101.129.69
stackoverflow.com.      118     IN      A       151.101.193.69
stackoverflow.com.      118     IN      A       151.101.1.69
stackoverflow.com.      118     IN      A       151.101.65.69

> echo $(ping -n 1 -w 1 stackoverflow.com | awk '/Pinging/')
Pinging stackoverflow.com 1 with 32 bytes of data:

> echo $(ping -n 1 -w 1 stackoverflow.com | awk '/Pinging/ {print $3}')
1

> ping -n 1 -w 1 stackoverflow.com | awk '/Pinging/ {print $3}'
[127.0.0.1]

ベストアンサー1

問題は、コマンド置換自体が引用されないことです。コマンド置換がコマンドの出力をecho2番目のコマンドの引数として使用する場合、echoコマンドの結果は単語分割とファイルグロービングの影響を受けます。コメントで述べたように、角かっこ内の文字は名前が[127.0.0.1]正確に1文字で、、、、またはいずれかのファイルと一致します(このパターンはシェル、無視、およびディレクトリリンクにのみ一致します)。というファイルを作成すると、結果を複製できます。1270....1

コマンド置換の結果がワイルドカードの影響を受けないようにするには、コマンドを二重引用符で囲む必要があります。

echo "$(echo "This will show an IP address in square brackets: [127.0.0.1]")"

また、GregのWikiで次の関連記事を参照してください(特に、内部および外部二重引用符を置き換えるコマンドの必要性を扱う最初の記事)。

おすすめ記事