在shell中创建文件然后替换里面的文本

时间:2017-05-09 19:01:37

标签: bash shell replace

我有一个脚本,我声明变量然后创建一个文件,然后替换该文件中的变量,这是我的示例脚本

#!/bin/bash

DMNAME = mydomain.com

cat <<EOF > /etc/nginx/conf.d/default.conf

server_name DMNAME;
root /usr/share/nginx/html/;
index index.php index.html index.htm;

ssl_certificate /etc/letsencrypt/live/DMNAME/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/DMNAME/privkey.pem;
EOF

sed -i 's/DMNAME/mydomain.com/g' /etc/nginx/conf.d/default.conf

#

这是用mydomain.com替换DMNAME的正确方法吗?

2 个答案:

答案 0 :(得分:1)

#!/bin/bash

DMNAME="mydomain.com"

cat <<EOF > /etc/nginx/conf.d/default.conf
server_name $DMNAME;
root /usr/share/nginx/html/;
index index.php index.html index.htm;

ssl_certificate /etc/letsencrypt/live/$DMNAME/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/$DMNAME/privkey.pem;
EOF

答案 1 :(得分:0)

@Bor是正确的,他在创建时用/etc/nginx/conf.d/default.conf填充正确的值 如果您想多次使用default.conf,则不应让sed使用-i选项更改文件,而是将结果重定向到所需的文件。

# Answer: do not use this here: DMNAME = mydomain.com

cat <<EOF > /etc/nginx/conf.d/default.conf
server_name DMNAME;
root /usr/share/nginx/html/;
index index.php index.html index.htm;

ssl_certificate /etc/letsencrypt/live/DMNAME/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/DMNAME/privkey.pem;
EOF

# And now DMNAME="mydomain.com" (without spaces, quotes are optional here).
# or for different domains

confpath="/etc/nginx/conf.d"
for domain in mydomain.com yourdomain.com hisdomain.com; do
   sed "s/DMNAME/${domain}/g" "${confpath}"/default.conf > "${confpath}"/${domain%.*}.conf
done