简体   繁体   English

如果数据在linux中不存在,如何将数据添加到文件中

[英]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.我正在使用基于 php 的 Web 应用程序,我只需要使用 https 访问,但 http 也接受。

and to install web application i am using a shell script file(ex: install.sh) where it will install all requirements by running it.为了安装 Web 应用程序,我使用了一个 shell 脚本文件(例如:install.sh),它将通过运行它来安装所有要求。

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.我想在 httpd.conf 中为 http 访问添加一个重定向规则,因为我需要在 install.sh 中添加一些逻辑,在 httpd.conf 中添加重定向规则,但它没有添加我的逻辑。

https redirect logic need to add in httpd.conf https重定向逻辑需要在httpd.conf中添加

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

install.sh安装.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我是 linux 新手,任何人都可以帮助我如何将数据附加到文件中,如果它不存在

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM