If I run this command on the command line (on my Mac OS X):
echo -n "hello" > foo-cmd.txt
I get the expected result, namely a file foo-cmd.txt containing "hello" without any newline at the end.
However, if I run this PHP code:
<?php
shell_exec("echo -n \"hello\" > foo-php.txt");
?>
I get a file foo-php.txt containing the text "-n hello" followed by a newline! In other words, the argument -n sneaks in as output, instead of being treated as an argument!
How can I resolve this issue?
asked Jul 5, 2012 at 10:50
Enchilada
3,9171 gold badge42 silver badges69 bronze badges
2 Answers 2
Your command is using the shell's built-in version of echo which doesn't support the -n option.
Try /bin/echo instead.
answered Jul 5, 2012 at 10:55
Alnitak
341k72 gold badges420 silver badges503 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Enchilada
How do you figure out (from system to system, or from one PHP version to another) whether shell_exec is using its own built-in version of a particular command?
Alnitak
@Enchilada it's not
shell_exec that has the problem - it's the system shell that shell_exec invokes that has the built-ins. The simple answer is, don't use shell_exec for something that could have been trivially done with a few lines of PHP code.Try this:
shell_exec("echo\ -n \"hello\" > foo-php.txt");
answered Jul 5, 2012 at 10:52
Shehzad Bilal
2,5132 gold badges19 silver badges27 bronze badges
Comments
lang-php