'how to add data into a file if the data doesn't exist in linux

i am using a php based web application and i need to access only with https but http also accepting.

and to install web application i am using a shell script file(ex: install.sh) where it will install all requirements by running it.

i want add a redirect rule for http access in httpd.conf for that i need to add some logic in install.sh which adds redirect rule in httpd.conf but it is not adding with my logic.

https redirect logic need to add in httpd.conf

<VirtualHost *:80>
       ServerAlias *
       RewriteEngine On
       RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [redirect=301]
</VirtualHost>

install.sh

#!/bin/bash
sudo grep -qxF '<VirtualHost *:80>\n    ServerAlias *\n    RewriteEngine On\n    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [redirect=301]\n</VirtualHost>' /etc/httpd/conf/httpd.conf
if [ $? -eq 0 ]; then
   sudo sed -i "$ a <VirtualHost *:80>\n    ServerAlias *\n    RewriteEngine On\n    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [redirect=301]\n</VirtualHost>" /etc/httpd/conf/httpd.conf
fi

i tried above code but it not working

i am new to linux can anyone please help me how to append the data to a file if it doesn't exist



Solution 1:[1]

This script is working for me:

    #!/bin/bash
    
#Here we replace spaces, newlines, tabs with nothing, to easy comparision using grep
    cat /etc/httpd/conf/httpd.conf | sed ':a;N;$!ba;s/\n//g' | sed 's/ //g' | sed 's/\t//g' | grep -F '<VirtualHost*:80>ServerAlias*RewriteEngineOnRewriteRule^(.*)$https://%{HTTP_HOST}%{REQUEST_URI}[redirect=301]</VirtualHost>'
    if [ $? -eq 1 ]; then
        echo -e "<VirtualHost *:80>\n    ServerAlias *\n    RewriteEngine On\n    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [redirect=301]\n</VirtualHost>" >> /etc/httpd/conf/httpd.conf
    fi

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IvanMikhalka