Bash script to update path to SSL certificate file

2019-07-24 12:11发布

问题:

I am creating a reusable script for automating the setup of new SSLs on server setups. I have a few different lines that need to get the file paths updated.

The defaults in the ssl.conf file look like this (Has leading # tag):

#SSLCACertificateFile /etc/pki/tls/certs/ca-bundle.crt

I need it to be dynamically set in the bash script, to end up like this:

 SSLCACertificateFile /etc/pki/tls/certs/example-ca-bundle.crt

So far I started out with this, but i'm not sure what I'm doing.

~/update_ssl_conf.sh

Code:

#!/bin/bash
SSL_CONFIG_PATH="/etc/httpd/conf.d/ssl.conf"

SSL_DEFAULT_CA_CERT_PATH="#SSLCACertificateFile /etc/pki/tls/certs/ca-bundle.crt" 
SSL_CA_CERT_PATH="SSLCACertificateFile /etc/pki/tls/certs/example-ca-bundle.crt"

I tried starting with the accepted solution linked below, and adding in a # after \b.

Bash script to update path to ssl certificate file in ssl.conf

sed -i "s|.*\b#$SSL_DEFAULT_CA_CERT_PATH\b.*|$SSL_CA_CERT_PATH|" SSL_CONFIG_PATH

and

sed -i "s|(?s).*(?<!\\w)$SSL_DEFAULT_CA_CERT_PATH(?!\\w).*|$SSL_CA_‌​CERT_PATH|" $SSL_CONFIG_PATH

I have a feeling neither are working because the regular expression is not 100% correct.

回答1:

You can use groups with () to match group of expressions :

SSL_CONFIG_PATH=/etc/httpd/conf.d/ssl.conf

SSL_CA_CERT_PATH=/etc/pki/tls/certs/example-ca-bundle.crt

sed -ri "s|(.*#)(SSLCACertificateFile)\s+(.*)|\2 $SSL_CA_CERT_PATH|" $SSL_CONFIG_PATH
  • (.*#) match the comment
  • (SSLCACertificateFile) match the field name
  • (.*) match the value

Only the field name (group 2 \2) is required following by your new path