# Bash to find all placeholder variables in a file and replace will real variables

I am looking to make a generic config file using variables such as: $PLACEHOLDER_USER Then after moving the file into the correct position I want to replace every instance of *$PLACEHOLDER_VARIABLE* into the value of $VARIABLE from my settings.sh file. In the example below *"$PLACEHOLDER_USER"* in log.conf would be replace by "tom"

log.conf

deploy = $PLACEHOLDER_USER  settings.sh USER="tom"  deploy.sh FILE="/home/logging/log.conf" ln -s /home/log.conf$FILE
do
sed -i "s/\$PLACEHOLDER_$variable/$value/g"$FILE
done < settings.sh


Is there a better way of doing this?

First up, the shell variable USER is already defined in bash, and is the log-in name of the current user.... so, if you log in as 'rolfl' then echo $USER will print rolfl. There are a number of programs and other systems that may be confused if you change the USER environment variable the way you have. Next, I don't think that the symbolic link you create does what you think it does: ln -s /home/log.conf$FILE


This will try to create a symbolic link at /home/logging/log.conf that points to the (presumably pre-existing) file /home/log.conf

This means that whenever anyone processes your settings script, they all modify the same file /home/log.conf and, since the first person will replace the tokens with their name, the other users will have nothing to do....

I presume the line:

ln -s /home/log.conf $FILE  should be cp /home/log.conf$FILE


Apart from this though, the program seems reasonable (I have not run it). My only comment is that this uses relatively advanced features of the shell. In my experience, it is often better to write these things in perl because people expect perl to do more complicated things. I don't know if this is sounding right, but, even though perl may be slower than this solution, it is also something that sys admins are familiar with, and will be happier to maintain than a complex shell script.... Still, if the people maintaining this code are familiar with what you are doing (and the fact that you are asking on CodeReview rather than using your peers is a suggestion that is not the case) then I would say it is fine.

• In the code, the shell variable USER is never modified. The settings file is parsed, not sourced. Nov 26 '13 at 16:11
• @MarkReed - I must have been side-tracked by the .sh extension on the file ;-) but still, the current code does not suggest it changes the \$USER variable. I will leave my comment as a warning to others not to use it anyway, it can be very confusing. Nov 26 '13 at 16:13