Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php shell_exec adds unwanted line break

Why does php's shell_exec command add an unwanted line break (\r\n) to the output and how can I prevent that?

test.php:

<?php
var_dump(shell_exec('echo "test"'));

running php test.php results in:

string(5) "test
"
like image 349
Horen Avatar asked Jan 29 '26 01:01

Horen


2 Answers

The echo command adds the line break so your example works as expected. If you want to remove it just use trim:

var_dump(trim(shell_exec('echo "test"')));

This will output:

string(5) "test"
like image 86
rekire Avatar answered Jan 30 '26 16:01

rekire


You can pass -n as argument to your echo command, this will prevent echo from outputting a trailing newline.

From the manual:

-n do not output the trailing newline

like image 23
user703016 Avatar answered Jan 30 '26 16:01

user703016



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!