我需要從 php 檔案運行一個 bash 腳本。這是我的嘗試...
$old_path = getcwd();
chdir('/home/svradmin/scripts');
$output = shell_exec('./testbash.sh');
chdir($old_path);
我testbash.sh的如下..
#!/bin/bash
echo "Hello World"
這很好用......現在我需要從我的 php 函式中傳遞一個變數,并據此 bash 腳本應該運行.. 舉個例子..
function fcn1() {
$old_path = getcwd();
chdir('/home/svradmin/scripts');
$output = shell_exec('./testbash.sh');//need to pass variable 'fcn1'
chdir($old_path);
}
function fcn2() {
$old_path = getcwd();
chdir('/home/svradmin/scripts');
$output = shell_exec('./testbash.sh');//need to pass variable 'fcn2'
chdir($old_path);
}
所以bash腳本需要改變如下,
#!/bin/bash
//If variable fcn1 received
echo "Hello World!! fcn1 has executed.."
//If variable fcn2 received
echo "Hello World!! fcn2 has executed.."
uj5u.com熱心網友回復:
例子
只需在通話后放置您的變數-
$output = shell_exec('./testbash.sh your_var_1 your_var_2');
然后在你的 bash 腳本中:
#!/bin/bash
var1=$1
var2=$2
echo "Hello World, var 1 is $var1 and var 2 is $var2"
更新
所以你的函式看起來像:
function fcn2() {
$old_path = getcwd();
chdir('/home/svradmin/scripts');
$var = "Hello Hello";
// Or as Fravadona suggested:
$var = escapeshellarg("Hello Hello");
$output = shell_exec("./testbash.sh $var");
chdir($old_path);
return $output;
}
function fcn1() {
$old_path = getcwd();
chdir('/home/svradmin/scripts');
$var = "Hello";
// Or as Fravadona suggested:
$var = escapeshellarg("Hello");
$output = shell_exec("./testbash.sh $var");
chdir($old_path);
return $output;
}
echo fcn1();
echo fcn2();
還有你的 ..
#!/bin/bash
var=$1
echo "Hello World!! $var has executed.."
uj5u.com熱心網友回復:
備注:要將 PHP 變數的內容傳遞給 shell,您絕對需要對其進行轉義:
$var='fcn1'
$output = shell_exec('./testbash.sh'.' '.escapeshellarg($var));
然后,您可以安全地將其用作引數:
#!/bin/bash
echo "Hello World!! $1 has executed.."
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/493694.html
上一篇:cksum命令無法識別-a選項
