一重引用符と二重引用符を使用して文字列からコマンドを実行します。

一重引用符と二重引用符を使用して文字列からコマンドを実行します。

二重引用符と一重引用符が必要なbashスクリプトでコマンドを実行したいと思います。

私が実行したいコマンドは次のとおりです。

some_command --query "'val' is not null"

私が達成したいのは、このコマンドをビルドし、bashスクリプトで実行することです。

command='some_command --query " 'val' is not null "'
output=$($command)
# + some_command --query '"' val is not null '"'

command='some_command --query \" 'val' is not null \"'
output=$($command)
# + some_command --query '\"' val is not null '\"'

ところで、コマンドが引用符で囲まれているため、実際のコマンドの構文が正しくありません。

文字コードを使用したり、配列でコマンドを作成して実行したりするなど、さまざまな方法を試しましたが、役に立ちませ"${array[@]}"んでした。

修正する: bashバージョンを使用して実行しています。GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

ベストアンサー1

複雑なコマンドを単純な変数に入れようとすると、失敗するしかありません。もっとコマンドを変数に入れようとしましたが、複雑な場合は常に失敗します!

おそらくあなたがしたいことはbashを通して最もよく達成されます。機能

実際に変数を使用するには、bash配列を使用します。

command=(some_command --query " 'val' is not null ")
"${command[@]}"

command以下を使用して、配列の実際の値を表示できますdeclare

$ declare -p command
declare -a command=([0]="some_command" [1]="--query" [2]=" 'val' is not null ")

私たちはこれが周囲の一重引用符を保存していることがわかりますval

はい

$ command=(echo -E " 'val' is not null ")
$ "${command[@]}"
 'val' is not null 

おすすめ記事