Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminal passing arguments from variable containing whitespace

Tags:

shell

php

ubuntu

In terminal how to pass a string as param that contains whitespace . It actually skips the part coming after whitespace and only takes the first word .

$word = 'soccer ball'
shell_exec('casperjs test.js --word='.$word);

So how can I escape the whitespace it only runs this command

casperjs test.js --word=soccer
like image 749
narek Avatar asked Oct 21 '25 03:10

narek


2 Answers

For cases like the one you describe (there are other special characters next to space in shell), PHP has the escapeshellarg function:

$word    = 'soccer ball';
$command = sprintf('casperjs test.js --word=%s', escapeshellarg($word));
$result  = shell_exec($command);

I takes care to preserve the value of $word as one argument:

casperjs test.js --word='soccer ball'

See as well:

  • detecting dangerous unix command line metacharacters
like image 114
hakre Avatar answered Oct 22 '25 19:10

hakre


Try enclosing it in quotes:

casperjs test.js --word="soccer ball"
like image 27
ladenedge Avatar answered Oct 22 '25 18:10

ladenedge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!