Bash機能で正しい見積もりエスケープ/保存

Bash機能で正しい見積もりエスケープ/保存

端末に2つのパラメータを指定して次のコマンドを入力すると、必要な操作が実行されます。

mycommand 'string that includes many spaces and double quotes' 'another string that includes many spaces and double quotes'

これで上記の内容をbashスクリプトに移動しました。

C=mycommand 'string that includes many spaces and double quotes'
function f {
 $C $1
}
# let's call it
f 'another string that includes many spaces and double quotes'

明らかに、これは同じ結果も有用な結果も生成しません。ただし、引用符、スペースを保持、および/または適切にエスケープし、実際の引数を保持する正しい方法を見つけることができません。私の注文2として扱われます。

私はMacでGNU bashバージョン3.2.57を使用しています。

ベストアンサー1

各引数を引用すると、位置引数として正しく処理されます。

#!/usr/local/bin/bash
f() {
  echo "function was called with $# parameters:"
  while ! [[ -z $1 ]]; do
    echo "  '$1'"
    shift
  done
}
f "param 1" "param 2" "a third parameter"
$ ./459461.sh
function was called with 3 parameters:
  'param 1'
  'param 2'
  'a third parameter'

ただし、含める(つまり最も外側の)引用符は次のとおりです。いいえパラメータ自体の一部です。少し異なる関数呼び出しを試してみましょう。

$ tail -n1 459461.sh
f "them's fightin' words" '"Holy moly," I shouted.'
$ ./459461.sh
function was called with 2 parameters:
  'them's fightin' words'
  '"Holy moly," I shouted.'

'出力にコピーされたパラメータの周りのsは、パラメータecho自体ではなく関数のステートメントからのものです。

サンプルコードを引用符でよりよく認識させるには、次のようにします。

C=mycommand
f() {
  $C "unchanging first parameter" "$1"
}
# let's call it
f 'another string that includes many spaces and double quotes'

またはこれ:

C=mycommand
f() {
  $C "$1" "$2"
}
# let's call it
f 'Some string with "quotes" that are scary' 'some other "long" string'

おすすめ記事