omg omg - 5 months ago 12
PHP Question

How do I write a converter to change a PHP file into a Bash file?

My so far not-so-bad version to implement this is:

function bashFileConvert($file)
return preg_replace('/([^\/\s]+\s+[^\/]+)(\/|$)/','"${1}"${2}',$file);

which mostly processes the problem when there is a space in the file name,like

$flie = '/usr/local/my test file.txt'

while will not be recognizable for Bash.

So I need to convert to

$file = '/usr/local/"my test file.txt"'

before calling something like:

exec('ls ' . $file);

But there are still many other corner cases, like the quote and '&' problem.

So, is there a ready version to do this job?


Now I tried escapeshellarg(), but it is a little strange here:

$file = '/usr/local/apache2/resumes_txt/5/San Francisco/qtzhang/Device "Engineer"/Job Resume Qintao Zhang.pdf.txt';
echo escapeshellarg($file);

D:\\test>php test.php
"/usr/local/apache2/resumes_txt/5/San Francisco/qtzhang/Device Engineer /Job Resume Qintao Zhang.pdf.txt"

It seems with this function, a quote is replaced with a space.


The solution is to use the escapeshellarg function in PHP (

$file = escapeshellarg('/usr/local/my test file.txt');

exec('ls ' . $file);

It will wrap quotes round it and escape quotes for you.