passing bash variable to perl command in bash script

Recently I tried passing a bash variable to perl command in bash script, it didn’t end well.

Troy Engel from http://tacticalvim.wordpress.com/ was nice enough to point out the issue:

use sed instead of perl for what you need; it’s simpler, faster and uses the bash variables easily.

I set up a test script /home/someuser/test.sh to show:

===
# cat test.conf
A=domain
B=PATH_DEST
===
# cat test.sh
domain="test"
PATH_DEST_APACHE="/test"
PATH_DEST_CONFIG="/home/someuser/${domain}.conf"

sed -i "s|domain|${domain}|g" "${PATH_DEST_CONFIG}"
sed -i "s|PATH_DEST|${PATH_DEST_APACHE}|g" "${PATH_DEST_CONFIG}"
===
# sh -x ./test.sh
+ domain=test
+ PATH_DEST_APACHE=/test
+ PATH_DEST_CONFIG=/home/someuser/test.conf
+ sed -i 's|domain|test|g' /home/someuser/test.conf
+ sed -i 's|PATH_DEST|/test|g' /home/someuser/test.conf
===
# cat test.conf
A=test
B=/test
===

What’s important to note is that A, you *must* use double-quotes in the sed expression so that variable expansion works; single-quotes inhibits expansion. B, as you found out, you need to use something other than “/” as your expression separator since you have a replacement variable with that character in it. I used pipes in sed, but you could use almost anything (“#”, etc.) for the same effect.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.