1

I'm trying to programatically create a PHP file:

<?php
if (!empty($_GET['code'])
{
  // Do 1
}
else
{
  // Do else
}
?>

I've got this:

sudo echo '<?php
if (!empty($_GET['code']))
{
}
else
{
}
?>' | sudo tee -a /var/www/html/index.php

But that's stripping out the single quotes from around the code ... I've tried all sorts such as double quotes and escaping the single quotes.

I'm sure this is simple! Help! :)

  • 1
    Did you try double quotes around `code` and single quotes around it all? – Adder Mar 02 '18 at 11:31
  • That did it. :) Thanks! – chris peckham Mar 02 '18 at 11:35
  • @Adder that's definitely a way around. Thought this approach is generally troublesome when applied to other (more complicated) scenarios. Please see my answer on how it's recommended to do by `shellcheck` (which is a very nice shell linter). – ddnomad Mar 02 '18 at 11:45
  • 1
    `sudo echo` is just silly. There is absolutely no need to obtain root privileges to write to standard output. – tripleee Mar 02 '18 at 13:42

1 Answers1

1

This is how single quotes should be escaped in bash and pretty much any shell:

echo '<?php
if (!empty($_GET['\'code\'']))
{
} else {
}
?>' | tee /var/www/html/index.php

See also: https://github.com/koalaman/shellcheck/wiki/SC1003

ddnomad
  • 373
  • 3
  • 15