I have a problem with my php-script when I call shell_exec
and pass a regular expression.
PHP code :
shell_exec("sh myscript.sh 'FOO\s*ONE'");
myscript.sh :
result=$(grep -c "${1}" myLongFile.txt)
echo ${result}
Like this, it returns 0
but if il call directly with cmd grep -c "FOO\s*ONE" myLongFile.txt
it returns 23
.
And if i replace in my php script \s
by the class [[:space:]]
it's working, but I have to use \s
I tried many solutions but failed.
Thank you all,
I find the solution, i just add option -P for grep in my script like this :
result=$(grep -P -c "${1}" myLongFile.txt)
Now, i can use \s
-P, --perl-regexp Interpret PATTERN as a Perl regular expression.
You have to escape the \
character with an other \
, so it becomes:
shell_exec("sh myscript.sh 'FOO\\s*ONE'");
You need to escape the backslash:
shell_exec("sh myscript.sh 'FOO\\s*ONE'");
The problem is not the escaping, but simply because grep
is POSIX based; this is why you should use [[:space:]]
instead of \s
. Some versions of grep
support PCRE syntax using the -P
option, but using POSIX is more portable.
Also, if you want to pass a variable from PHP to a shell script it's advisable to use escapeshellarg()
:
$re = 'FOO[[:space:]]*ONE';
shell_exec(sprintf("sh myscript.sh %s", escapeshellarg($re)));
It should be mentioned that escapeshellarg()
doesn't work consistently between Windows and Linux (and even between shells); in some cases you need to apply addcslashes()
.