更改shell_exec中的目录不起作用

I have this routine for running BASH-scripts:

// $cmd is something like '/var/tmp/script.sh'
function runshell($cmd)
{
    $work_dir = dirname($cmd);
    $work_file = basename($cmd);
    $message = shell_exec("cd " . $work_dir . " && " . $work_file . " 2>&1");
    return $message;
}

The problem is that it doesn't change directory and $work_file is never found

Solution1

Use full path to file

$message = shell_exec($work_dir . "/" . $work_file . " 2>&1");

Solution2

Also you can use chdir() for this. It will change current working directory of the php script.

chdir($work_dir);
$message = shell_exec($work_file . " 2>&1");