You are not logged in.

#1 2020-11-23 15:08:39

Smith oo4
Member
From: Calgary, Alberta, Canada
Registered: 2007-12-30
Posts: 42

The Best way to script writing multiple lines to a file

I am looking for the “best” way to script writing multiple lines to a file when the lines contain special character, e.g. Nginx configs. Below is the best I have come up with so far:

sudo sh -c 'cat > /etc/nginx/sites-enabled/sonarr.your-domain.xyz << EOF
server {
    listen         80;
    server_name    sonarr.your-domain.xyz;

    auth_basic                  "Restricted";
    auth_basic_user_file        /etc/nginx/.htpasswd;
    
    location / {
        proxy_pass              http://127.0.0.1:8989;
        proxy_set_header        X-Real-IP       \$remote_addr;
        proxy_set_header        Host            \$host;
        proxy_set_header        X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto \$scheme;
        proxy_redirect          off;
        proxy_buffering         off;
    }
}
EOF

This works however I am not a big fan of having to go through and escape all special characters, e.g. find and replace $ with \$.

Does anyone have a better suggestion?

Offline

#2 2020-11-23 18:07:44

tors42
Member
Registered: 2020-11-14
Posts: 4

Re: The Best way to script writing multiple lines to a file

If you quote your delimiter word (EOF), it won't expand variables.
I.e

$ cat > myfile << "EOF"
$ $ $
EOF
$ cat myfile
$ $ $

Offline

#3 2020-11-23 19:03:19

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: The Best way to script writing multiple lines to a file

A fine explanation is done in wooledge wiki; http://mywiki.wooledge.org/BashGuide/In … erestrings
Wikipedia has a good written piece too also explains use of single quotes & backtics also; https://en.wikipedia.org/wiki/Here_document#Unix_shells

Offline

#4 2020-11-23 20:26:49

Smith oo4
Member
From: Calgary, Alberta, Canada
Registered: 2007-12-30
Posts: 42

Re: The Best way to script writing multiple lines to a file

Nice, and thank you for the extra resources

Offline

Board footer

Powered by FluxBB