2

I have a command (php file) which takes, as an argument, the location of a file.

eg.

$ php ./ScriptName.php /my/file/location.txt

Sometimes I only need one or two words, so I don't really want to create the location.txt file just so I can reference it with the next command - I'd rather pipe it with the command somehow. For example, consider the contents of location.txt from the above example being just:

mywords

Is there a way I can rewrite that original commandline argument to just provide the contents of a "virtual" file?

1

2 Answers 2

3

You can use a variant of the /dev/fd/0 trick to pass a string to a script which expects a file name:

php ./ScriptName.php php://fd/0 <<<'mywords'

For example, script.php contains:

<?php
   $handle=fopen($argv[1],"r");
   echo "Read: ".fgets($handle);
   fclose($handle);
?>

Running:

php script.php php://fd/0 <<<'Some text'

outputs:

Read: Some text
4
  • Running GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu) this did not work - I got Warning: fopen(/dev/fd/0): failed to open stream: No such file or directory Dec 5, 2016 at 20:05
  • Perhaps this is more of a problem with php fopen than bash... Dec 5, 2016 at 20:10
  • Sorry, I was way behind the times. Edited answer with the correct syntax accepted by PHP independent of the shell.
    – AlexP
    Dec 5, 2016 at 20:22
  • Thank you, your example and commands do work. I am actually trying to pipe this through the symfony console, which is still giving me trouble though. Perhaps I will re-ask on SO for the symfony specific nature of this now. Dec 5, 2016 at 20:49
3

If you have a shell that allows process substitution such as zsh, bash or ksh, you could do

php ScriptName.php <(echo mywords)

The shell will set up some method to run the echo command in a different shell, and make the output available either as a named fifo or more commonly via a pipe and a filename of the form /dev/fd/XX.

2
  • Running GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu) this did not work - I got Warning: fopen(/dev/fd/63): failed to open stream: No such file or directory Dec 5, 2016 at 20:03
  • 1
    Perhaps this is more of a problem with php fopen than bash... Dec 5, 2016 at 20:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .