Skip to content
Advertisement

Reading user command line input with PHP with readline, but bash is not default shell

I wrote a PHP script and I’m trying to read user input from the command line. I started of with

$myVar = exec('read myVar; echo $myVar;');

which worked fine, but when typing the input the arrow keys didn’t work the way it should. I learned that this could be solved with the -e switch, so it became:

$myVar = exec('read -e myVar; echo $myVar;'); 

Now this worked like a charm in my development envionment but unfortunately it seems like in our production environment PHP doesn’t use a bash shell and doesn’t support the -e switch, and it’s probably not easy to change this.

According to the third answer to this question one can force PHP to use bash, so it became:

$myVar = exec('/bin/bash -c "read -e myVar; echo $myVar"');

Now, unfortunately this doesn’t work as the variable myVar is not set.

When I run the commands directly from the command line $myVar (the shell variable) is set with whatever my input is, and consequently echo’ed

However when using the -c option, either in a PHP-exec() or directly on the command line like this:

/bin/bash -c "read -e myVar; echo $myVar";

$myVar isn’t set at all, and an empty string (or whatever was the previous value of $myVar) is echo’ed

What do I do wrong here?

Advertisement

Answer

The issue is that $myVar is being interpreted before being passed to bash. The following will work by escaping the $ before it’s passed to the shell:

/bin/bash -c "read -e myVar; echo $myVar"

Also you can shorten it a little by making use of $REPLY

/bin/bash -c "read -e; echo $REPLY"

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement