2

is it possible for shell_exec to execute a given command, where the initial command would ask the for a dynamic input then followed by a command that's based on the input itself.

i've researched for hours for the answer and i can't seem to find what i'm looking for.

i have a requirement that's similar to the idea of the example below and any help would be appreciated since

$x = shell_exec("read -p 'Enter your name : ' x; echo 'Your name is' : $x");

echoing x outputs :

your name is

as you can see i'm running multiple commands, but i do not know where i can insert inside the string command for the input.

note : i tried doing

$x = shell_exec("echo 'Foo' | read -p 'Enter your name : ' x; echo 'Your name is :' $x");

echo $x;

output was :

Your name is :

i was expecting like

Your name is : Foo

clearly, something is wrong.

4
  • what shell commands do you actully want to run ? Commented Jul 31, 2012 at 9:44
  • you need to escape $x inside the string $x = shell_exec("read -p 'Enter your name : ' x; echo 'Your name is' : \$x"); Commented Jul 31, 2012 at 10:36
  • i tried adding \ after the $x, the output was "your name is : $x" Commented Jul 31, 2012 at 12:25
  • @Dagon it's pretty long, related to fabric script (python) and php, basically, the idea is after i run that script, the server will ask me for a user password after the initial shell command, this has to be run from php because i will be supplying dynamic data to the command (concat variables to the command string) Commented Jul 31, 2012 at 12:27

1 Answer 1

1

I've come across the same problem as you with read other times. If you execute the same line on the terminal, the result is the same, so this is not a php issue, but a shell issue:

$ echo 'Foo' | read -p 'Enter your name : ' x; echo "Your name is : $x"
Your name is : 

If you wrap the read inside a while .. do .. done, then it all works perfectly:

$ echo 'Foo' | while read -p 'Enter your name : ' x; do echo "Your name is : $x" ; done
Your name is : Foo

I don't know why this happens though.

Also you can try using proc_open and similar, and you'll get more control of the input/output streams, but I don't know whether they will work with the read issue.

Sign up to request clarification or add additional context in comments.

1 Comment

/ mogria your combined suggestions have gave me the answer, with a lil trial and error, $x = shell_exec("echo 'foo' | while read -p 'enter your name : ' x; do echo 'your name is : ' \$x; done;"); echo $x; has produced what i needed. thanks guys

Your Answer

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.