Bash insert config with special characters into wp-config.php

I’m trying to insert a config used to get the (presumably) real IP of visitors to our sites, into their respective wp-config.php, but I’m running into issues with the large number of special characters involved.

I plan on adding this to a bash script that spins up new WordPress installs quickly, but as it is I have to go in and manually add the line after each install.

Read More

This is the config…

$_SERVER['REMOTE_ADDR'] = preg_replace('/^([^,]+).*$/', '1', $_SERVER['HTTP_X_FORWARDED_FOR']);

A snipit of the wp-config.php:

$table_prefix = 'wp_';

define('WPLANG', '');



/* That's all, stop editing! Happy blogging. */ 

I originally thought I could insert the config in the whitespace under “define(‘WPLANG’, ”);” with sed as I’ve done with other similar tasks…

find="define('WPLANG', '');"
replace="$_SERVER['REMOTE_ADDR'] = preg_replace('/^([^,]+).*$/', '1', $_SERVER['HTTP_X_FORWARDED_FOR']);"

sed "s/$findnn/$findn$replace/"

…but the special characters are throwing everything off. I’ve tried numerous different ways of quoting and escaping but I’m not having any luck.

Related posts

Leave a Reply

1 comment

  1. You could easily do this with awk:

    awk -vrep="$replace" '{print}/define.*WPLANG/{print RS rep}' wp-config.php
    

    This prints every line unconditionally. When a line containing “define” and “WPLANG” is matched, it also prints the value of the shell variable $replace, with a newline before it.

    In order to avoid problems with escaping characters in bash, you can use cat with a HEREDOC:

    replace=$(cat <<'EOF'
    $_SERVER['REMOTE_ADDR'] = preg_replace('/^([^,]+).*$/', '1', $_SERVER['HTTP_X_FORWARDED_FOR']);
    EOF
    )
    

    The single quotes around 'EOF' mean that the characters in the string are interpreted literally.