8

I need to create the file /opt/nginx/conf.d/default.conf with this content via shell script and create the file if it doesn't exist:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    root /usr/share/nginx/html;
}

How do I write multiline content via a shell script?

I created the directory

sudo mkdir -p /opt/nginx/conf.d

But I don't know how to write a file.

12

summary : use >> to append, use [ -f file ] to test.

try

if [ ! -f myfile ]
then
   cat <<EOF > myfile
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name $server ;
    root /usr/share/nginx/html;
}
EOF
fi
  • the syntax cat <<EOF is called a "here document".
  • $server will be replace by its value, or empty if undefined.
  • as pointed out, you can use single quoted 'EOF' to avoid replacing var if any.
  • you can also have multiple echo (this could be painfull to maintain if too many echo)

    echo "## foo.conf" > foo.conf
    echo param1=hello >> foo.conf
    echo param2=world >> foo.conf
    

prepending

there is no direct prepend in bash, either use temporary file

mv file file_tmp
cat new_content file_tmp > file
rm file_tmp

or edit it

sed -i -e '1r new_file' -e 'wq' file
  • How would I prepend some multiline content to a file? – user3142695 Oct 4 '17 at 14:05
  • 1
    Another wise change to do would be to quote the here-doc limit strings, so that any words containing $ (if present) are not treated as variables and therefore not getting expanded – Inian Oct 4 '17 at 14:08
  • @user3142695 The easiest would be to write the here-document to a separate file and then cat the two files together and rename the result. – Kusalananda Oct 4 '17 at 14:12
  • If one wants to do many separate echos, it's still more efficient to have just one redirection, by putting them in a block: { echo "foo"; echo "bar"; echo "baz"; } >file -- that way we aren't re-opening file every time we just want to write a single line to it, and closing it when that line is done. – Charles Duffy Oct 5 '17 at 1:46
  • Another good use of here document: cat << EOF | sudo tee /opt/nginx/conf.d/default.conf ... – lp1051 May 2 '18 at 14:04
3

If the /opt/nginx/conf.d/default.conf file does not exist, then print(f) the static string into the file:

[ -f /opt/nginx/conf.d/default.conf ] || printf 'server {\n    listen 80 default_server;\n    listen [::]:80 default_server;\n    server_name _;\n    root /usr/share/nginx/html;\n}\n' > /opt/nginx/conf.d/default.conf
  • 1
    I'd consider printf '%s\n' "first line" "second line" perhaps a bit more readable; that way one doesn't need to read through the whole string to figure out where the escapes are.. – Charles Duffy Oct 5 '17 at 1:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.