I'm trying to write a script that updates a server config file to the latest format. The purpose of the script is to copy over existing (defined) variables to the latest config (in a temp file), then copy/overwrite the old config file with the newly generated one.
From my understanding, using double quotes will expand variables in sed
. This seems to work fine when only one variable is used in the pattern:
sed -i "s|random|$PASSWORD|g" /tmp/latest_config
In the above example, the temp config file is successfully modified, and all instances of random
are replaced with the value of $PASSWORD
. However, this doesn't work the other way:
sed -i "s|$PASSWORD|random|g" /tmp/latest_config
In the above example, nothing happens, and no sed errors etc. The value of $PASSWORD
in the temp config file is not modified...
NOTE: $PASSWORD
in the first example is being sourced from "old" config file at the top of this script, but the goal of the second example would be replacing variable value...
I've seen dozens of similar "variable" questions on the SE network, however many of the answers are wrong (e.g. using single quotes, etc) or simply do not work for me. I have tried many formats, including single and double quotation marks, brackets (to differentiate environment variable from the variable being actually searched for by sed
)... nothing has worked so far, e.g.:
sed -i "s|$PASSWORD|$PASSWORD|g" /tmp/latest_config
sed -i "s|$PASSWORD|${PASSWORD}|g" /tmp/latest_config
sed -i "s|\$PASSWORD|${PASSWORD}|g" /tmp/latest_config
sed -i 's|$PASSWORD|"${PASSWORD}"|g' /tmp/latest_config
sed -i 's|\$PASSWORD|"${PASSWORD}"|g' /tmp/latest_config
The only solution that works is a sort of hacky workaround:
sed -i "s|\(^PASSWORD=\).*|PASSWORD=\"$PASSWORD\"|g" /tmp/latest-config
Why? Do I need to export the existing variables first, or is this as good as it gets?...