0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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.
0

Try this:

shell_exec("echo\ -n \"hello\" > foo-php.txt");
answered Jul 5, 2012 at 10:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.