0

Is it possible to pass parameters from php to a shell script. For ex:

<?php

$var = "testfolder";

shell_exec('sh /path/test.sh');

?>

Shell script (test.sh):

sudo mkdir $var /path/

I want the value in php $var to be exported to the shell script to be able to create a folder with the name as in the variable. Is this possible?

I know already how to insert a variable into a string, but i can't figure out how to rewrite the line shell_exec to export this variable to my shell script

Thanks!

bhavish030
  • 53
  • 7
  • Yes, it's possible. What you pass to `shell_exec()` is just an ordinary string. Just concatenate or use variable interpolation like you would on any other string. – M. Eriksson Mar 02 '19 at 18:55
  • How can i edit this line to pass the value **$var** ? – bhavish030 Mar 02 '19 at 18:56
  • 1
    String interoplation (double quotes): `"mkdir $var"`. Concatenation: `'mkdir ' . $var`. Pick your favorite. You should also [read the manual](http://php.net/manual/en/language.types.string.php) about strings in PHP. – M. Eriksson Mar 02 '19 at 18:57
  • 1
    Possible duplicate of [PHP - concatenate or directly insert variables in string](https://stackoverflow.com/questions/5605965/php-concatenate-or-directly-insert-variables-in-string) – M. Eriksson Mar 02 '19 at 19:01
  • Thanks i understood how to insert `$var` into my string with the above link. But i can't figure out how to rewrite the line `shell_exec` in order to export the variable `$var` to my shell script. – bhavish030 Mar 02 '19 at 19:12
  • How about `shell_exec("foo $var bar")` or `shell_exec('foo ' . $var . ' bar')`? – M. Eriksson Mar 02 '19 at 19:18

2 Answers2

2

Yes.You need to pass the variables as arguments to the shell script, and the shell script has to read its arguments.

please check this link: passing a variable from php to bash

Nazmul
  • 21
  • 6
1

Pass the variable as a command line parameter to the shell script. For example:

<?php
$var = "testfolder";
echo 'php: ' . shell_exec("sh ./test.sh $var");
#!/bin/sh
echo "shell: $1"
$ php test.php
php: shell: testfolder

(For clarity, I'm simply echoing here.)

Shells transform command line parameters sequentially into variables $1, $2, etc.

nurikabe
  • 3,802
  • 2
  • 31
  • 39