Shell script: How can I write multiline content to file if the file doesn't exist?

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

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