0

I'm trying to write a bash script from within PHP. I have an array of functions to run that I want to append to the script, along with custom code snippets and other variables.

$my_array_of_bash_cmds =
Array (
    [0] => bash_cmd1
    [1] => bash_cmd2
    [2] => bash_cmd3
)

Using a simple heredoc such as:

$bash_script = <<<EOD
#!/bin/bash
cd {$path}
echo "You are in `pwd`."
{$my_array_of_bash_cmds}
EOD;

results in Array being echoed in php (v5.3.3). Is there a special way to handle arrays inside a heredoc? I can't find any info on this, only the reciprocal appending heredocs to arrays.

This $bash_script will eventually be written to a file obviously, so perhaps there's a better solution to what I'm trying to do. My efforts to research this have been fruitless, though. Any input would help.

stacked
  • 277
  • 3
  • 9
  • This has nothing to do with heredoc. You cannot concatenate an array to a string but need to use a function like [`implode()`](http://php.net/implode) first – kero Mar 12 '15 at 23:00
  • You would either need to explicitly state each command in the array `{$arr[0]}\n{$arr[1]}` or implode the array. – Jonathan Kuhn Mar 12 '15 at 23:01
  • Thank you both. My mistake for overlooking something so simple. – stacked Mar 12 '15 at 23:09
  • For anyone's future reference, `implode(PHP_EOL, $my_array)` will properly implode the array with the appropriate end of line character for the bash script execution. `\n` or `\\n` do not appear to work. – stacked Mar 12 '15 at 23:34

0 Answers0