catでMakefileドキュメントをリダイレクトすると、変数と改行文字が消えます。

catでMakefileドキュメントをリダイレクトすると、変数と改行文字が消えます。

実装する:

cat <<MAKE >> /etc/apache2/sites-available/Makefile1
% :
    printf '%s\n' \
    '<VirtualHost *:80>' \
    'DocumentRoot "/var/www/html/$@">' \
    'ServerName $@' \
    '<Directory "/var/www/html/$@">' \
    'Options +SymLinksIfOwnerMatch' \
    'Require all granted' \
    '</Directory>' \
    'ServerAlias www.$@' \
    '</VirtualHost>' \
    > "$@"
    a2ensite "$@"
    systemctl restart apache2.service
    mv /etc/apache2/sites-available/$@ /etc/apache2/sites-available/[email protected]
    # Before quotes == Tabuilations. Inside quotes == Spaces. After quotes == Spaces (1 space before backslash for line break). Also avoid any other spaces.
MAKE

以下を実行した後にこれを生成しますcd /etc/apache2/sites-available/ && make contentperhour.com

% :
printf '%s\n' '<VirtualHost *:80>' 'DocumentRoot "/var/www/html/">' 'ServerName ' '<Directory "/var/www/html/">' 'Options +SymLinksIfOwnerMatch' 'Require all granted' '</Directory>' 'ServerAlias www.' '</VirtualHost>' > ""
a2ensite ""
systemctl restart apache2.service
mv /etc/apache2/sites-available/ /etc/apache2/sites-available/.conf

ご覧のように、実行後の2番目の例の関連行は1つの長い行(バックスラッシュで表示される改行なし)であり、$@リダイレクト後にこれが発生するのはなぜですか?

ベストアンサー1

次のHere Documentsセクションでman bash

この文書の形式は次のとおりです。

     <<[-]word
            here-document
     delimiter

パラメータと変数の拡張、コマンドの置換、算術拡張、パス名の拡張は単語に対して行われません。 Wordに引用符が含まれている場合、区切り文字はWordから引用符を削除した結果であり、文書の行はここでは拡張されません。 単語が引用されていない場合、文書内のすべての行はパラメータ拡張、コマンド置換、および算術拡張を経て、文字の順序\は無視され、\は文字\、$、および`を引用するために使用する必要があります。

MAKEあなたの例では引用されていないので無視され、拡張され\ます$@(空のパラメータリストかもしれません)。

解決策は、マークアップの一部を引用することです。

cat <<\MAKE >> /etc/apache2/sites-available/Makefile1

または

cat <<"MAKE" >> /etc/apache2/sites-available/Makefile1

\\または、行の連続に必要な脱出を提供します\$@$@

おすすめ記事