“which”命令在PHP中不起作用

I have two remote servers that need to have a certain codebase in sync. I have it all set up on the first, but while setting it up on the second, I ran into a problem:

They don't have hg installed in the same location. I can't just run hg <command> because it returns the error:

sh: hg: command not found

So I had been using the full path, but that won't work with two separate hg locations.

I thought it would be clever to run which hg and use the path from the response, so here's the new code:

$hg = trim(`which hg`, "
");
$output = `{$hg} pull -u`

But $hg is NULL, so that doesn't work! I can ssh into the 2nd server and see that which hg definitely does work. I even appended 2>> path/to/log to see if there were any errors with the which command, but there was not. I made sure it was writing to the log, so it wasn't related to that.

I am not running in safe mode, and I am definitely allowed to run shell_exec because other commands work.

I know I could just create a symlink so they both had the same path and just hardcode the path, but it's driving me crazy why shell_exec('which hg') isn't working!!!

which hg will only work if hg is already in your path, otherwise it will return the empty string.

Obviously this is not what you want, since if it were already in your path, you could just use hg.

If you're using many machines with different configs, you could just create a bin directory in your home directory, add it to your path and make links to the commands you need in that directory. That will allow you to use the same commands on all machines.

For PHP, you'd need to put it in a directory accessible to the web server (but preferably outside the document root), besides that, you can use the same technique there by giving an absolute path to the common directory where you created your links.

try

shell_exec('/usr/bin/which hg');

instead. $PATH may not be set and that is a typical location of which