0

I need to read in a php template file in a bash script, then replace some variables in the template (can be anything, like $(variable)), and finally output the whole content to a new file.

I originally had

stuff=$stuff bash templatefile > newfile

for non-PHP files

cat <<END
//stuff
END

But my php template file looks something like

#!/usr/bin/php
<?php
//lots of php variables, so can't use bash variables that have the same $ prefix
?>

Because PHP also uses the $ prefix for its variables like bash, I can't easily pass in parameters. How would I go about it?

xiankai
  • 2,773
  • 3
  • 25
  • 31
  • can you just give an example as input and expecting output? – Kent Jul 25 '12 at 09:15
  • @Kent My input is the php file and the output is the php file with a replaced variable - However I'm not sure how to pass the bash variable in for the replacement. – xiankai Jul 25 '12 at 09:33
  • I think the operative question is: **Why** are you doing this? – sorpigal Jul 25 '12 at 11:39
  • @Sorpigal I was trying to create a bash script when setting up a new virtualhost, that creates a customised php script for that new virtualhost. This was meant to be a simple replacement though so I didn't think the context was relevant. – xiankai Jul 26 '12 at 03:14
  • @xiankai: It's relevant because what you are doing sets off danger bells in my head. Your PHP script is broken if it requires an external tool to modify it to work. Code is code; why not make the PHP script customize itself? Make it read a config file, at least. Then generate a new config file any way you like. There's no need to write shell code to generate php code; that's crazy. – sorpigal Jul 26 '12 at 11:20

1 Answers1

0

Try this answer: Bash Templating: How to build configuration files from templates with Bash?

This allows you to use ${varname} instead of $varname

Community
  • 1
  • 1
Oliver A.
  • 2,870
  • 2
  • 19
  • 21
  • I saw that question, but unfortunately the answer doesn't have anything about outputting the whole replaced file to a new file. – xiankai Jul 25 '12 at 09:36
  • 1
    You just have to rdirect the output to the new file. "> whatever.php" – Oliver A. Jul 25 '12 at 10:33
  • I ended up using the question asker's 2nd command like this: cat template.php | sed 's|\${stuff}|'$stuff'|' > newfile.php. Thanks for the nudge in the right direction! – xiankai Jul 26 '12 at 03:10