1

I'm a PHP newbie... I usually script with bash, where I can easily do something like this:

#!/bin/bash

# myscript.sh

function testFunction() {
 echo "bubu" > /dev/tty
 echo "gaga"
}
a=$(testFunction)
echo $a > t

If I run it in a shell I get this:

$ ./myscript.sh
bubu
$ cat t
gaga

Now, how can I get the same output if I have a PHP file instead of the function?

// my script.php
echo "bubu";
echo "gaga";

Bash script:

#!/bin/bash

# myscript.sh

a=$(php myscript.php)
echo $a > t

If I run it in a shell I get this:

$ ./myscript.sh
$ cat t
bubu
gaga

How can I tell the php script to send "bubu" to /dev/tty?

I tried and play around with ob_start and his friends, but didn't get any result.

masavini
  • 119
  • 1
  • 3
  • 10

2 Answers2

0

You could use stdout/stderr in PHP to split the output, see stackoverflow question PHP CLI doesn't use stderr to output errors. This would however require to adapt all "bubu" echo statements in myscript.php to something like:

fwrite(STDERR, "bubu");

You would then redirect stderr to file bubu in the Bash wrapper to get all the "bubu" lines, while all the "gaga" lines would appear on your terminal:

php myscript.php 2> bubu
Community
  • 1
  • 1
Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
  • thanks michael... but: is there a way in php to send something to stderr without writing to a file? it sounds pretty much expensive if running within a cicle, isn't it? – masavini Sep 17 '14 at 16:09
  • `fwrite` does not write to an actual file in this case, so there is no disk I/O in the PHP part. You should not call `fopen` for each write however, just do that once at program start. There is another way using [error_log()](http://php.net/manual/en/function.error-log.php), unless `error_log` is set to a specific file, but that further decreases performance compared to `fwrite`. My test setup (a simple loop) completed 10000 iterations with `echo` in 35 ms, with `fwrite` in 41 ms, and with `error_log` in 45 ms. – Michael Jaros Sep 17 '14 at 16:43
  • great, that's definitely sounds as a good solution... many thanks! – masavini Sep 17 '14 at 16:51
  • You don't even need to open that stream handle in command-line. I've edited the answer accordingly. – hakre Nov 15 '14 at 14:15
-2
$ php script.php > /dev/tty

That does the trick :)

edit/

I see, you want just the "bubu"

so, you should do the following:

file_put_contents('/dev/tty', 'bubu');
mariobgr
  • 2,143
  • 2
  • 16
  • 31
  • This will send everything there (which is already the default anyway in a way) and does not split the output the way the OP wants). – Etan Reisner Sep 17 '14 at 15:28