bash - 変数を介してheredocに空行を追加する

bash - 変数を介してheredocに空行を追加する

スクリプトでこのシナリオを使用する場合:

#!/bin/bash

addvline=$(if [ "$1" ]; then echo "$1"; echo; fi)

cat << EOF
this is the first line
$addvline
this is the last line
EOF

空の場合は$1空行が表示されます。しかし、空でない場合は、
その後に空白行を追加するにはどうすればよいですか?$1

したがって、スクリプトを実行すると、次のようになります。
bash script.sh hello

私は得るでしょう:

this is the first line
hello

this is the last line

echoの2番目のものを使用してこれを達成しようとしていますが、if statement改行文字は渡されません。

ベストアンサー1

ifコマンド置換を使わずに変数の内容を設定することにします。

if [ "$1" ]; then addvline=$1$'\n'; fi

それから:

#!/bin/bash
if [ "$1" ]; then addvline=$1$'\n'; fi
cat << EOF
this is the first line
$addvline
this is the last line
EOF

おすすめ記事