複数行のエラーメッセージでBashパラメータを置き換える

複数行のエラーメッセージでBashパラメータを置き換える

エラーメッセージでパラメータ置換を使用しています${var1:?'some message'}。たとえば、複数行のエラーメッセージをマージしました。現在は、単一引用符で囲み、Enterキーを使用して改行文字を挿入する場合にのみ正しく機能します。複数行を許可して個別に保存するための賢明な方法はありますか?

ただ探求したくて好奇心を感じました。直接の関係がない限り、ifステートメントに関連する代替構文を提案しないでください。

ケース:

動作:一重引用符

needed=${1:?'first error line
second error line
third error line'}

動作しません:他の文字列変数を呼び出す

usage_message='Please use this script by providing the following arguments:
1: <e.g user name>
2: <e.g run script>
3: <e.g something else>'

username=${1:?$usage_message}
run_script_path=${2:?$usage_message}
where_to_save=${3:?$usage_message}

機能しません:関数呼び出し

function get_message {
       echo -e "first line \nsecond line\nthird line"
       # or
       # printf "first line \nsecond line\nthird line"
}

needed=${1:? $(get_message)}

パラメータ置換の追加の議論: https://stackoverflow.com/a/77772942/13413319

ベストアンサー1

しかし、パラメータ拡張のためのPOSIX規格この問題については不明であり、割り当ての RHS は bash パラメータ拡張が実行される数少ない場所の 1 つです。いいえ単語分割1は通常行われます。この場合、単語分割2を防ぐために二重引用符で複数行変数を拡張する必要があるようです。だから

(引用しない)

$ username=${1:?$usage_message}
bash: 1: Please use this script by providing the following arguments: 1: <e.g user name> 2: <e.g run script> 3: <e.g something else>

(先頭)

$ username=${1:?"$usage_message"}
bash: 1: Please use this script by providing the following arguments:
1: <e.g user name>
2: <e.g run script>
3: <e.g something else>

また、見ることができますいつ二重引用符が必要ですか?


  1. 例えば

     $ var=foobar
     $ username=${var/bar/$usage_message}
     $ declare -p username
     declare -- username="fooPlease use this script by providing the following arguments:
     1: <e.g user name>
     2: <e.g run script>
     3: <e.g something else>"
    
  2. 明らかにワイルドカードではありませんが、たとえば

     $ word=*
     $ username=${1:?$word}
     bash: 1: *
    

おすすめ記事