Thursday, February 3, 2022

[SOLVED] Append a text to all files under specific folder

Issue

I need to append text to the bottom of the files into .htaccess files under /home directory for all of my client's website.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}`

I already tried to echo 'code' >> .htaccess and failed because it contains new line, I've also tried \n or \r without success and I'm using printf; I can add new line but it says

bash: printf: `}': invalid format character

Update..

Im successfully fix the invalid format character by following tripleee code but unfortunately it not append all of my .htaccess files

This is the code

for file in /home/*/public_html/.htaccess; do
    printf '%s\n' '# Redirect to https' \
        'RewriteEngine On' \
        'RewriteCond %{HTTPS} off' \
        'RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}' >>".htaccess"
done

Im able to resolved the issue by using these code

printf '%s\n' '# Redirect to https' \
        'RewriteEngine On' \
        'RewriteCond %{HTTPS} off' \
        'RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}'  |
tee -a /home/*/public_html/.htaccess

Thanks to tripleee


Solution

You need to double the % to produce a literal per-cent character in a printf format string. Or, pass an explicit format string to printf and pass the individual lines as arguments.

printf '%s\n' 'RewriteEngine On' \
        'RewriteCond %{HTTPS} off' \
        'RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}' |
tee -a /home/*/public_html/.htaccess >/dev/null

There's no reason you couldn't use echo too, though it's slightly hard on the eyes.

echo 'RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}' |
tee -a /home/*/public_html/.htaccess >/dev/null

You can get something similar with echo -e but it's less portable and less elegant than printf.

You could also simply use a here document:

tee -a /home/*/public_html/.htaccess<<-'____HERE' >/dev/null
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
____HERE

Putting a dash (minus) before the here-document separator allows you to use tabs (but not spaces!) for indentation; the leading tabs will be stripped from the text. Putting quotes around the separator causes the shell to quote the document (i.e. no dollar signs or backticks in the document will be evaluated).



Answered By - tripleee
Answer Checked By - Pedro (WPSolving Volunteer)