1

I want my bash script to find where PHP is installed - this will be used on different Linux servers, and some of them won't be able to use the which command. I need help with that second line:

#!/bin/bash
if (php is located in /usr/bin/php); then
    PHP = /usr/bin/php
else
    PHP = /usr/local/zend/bin/php
fi
$PHP script.php

5 Answers 5

4

Use this:

`which php`

But this is what I would do:

#!/bin/env php
<?php

require 'script.php';
3
  • 1
    You said to use which php in spite of the original post saying some wouldn't be able to have access to which. Also, you might have misread the question. He is trying to execute a PHP script through the command line, but in order to do that he needs the path to the PHP executable. How would a PHP require help him if he can't execute it? Feb 24, 2013 at 6:55
  • Hi Derek. Since you downvoted me for including "which", you should see that I provided both answers. Pretty much every single UNIX distribution has /bin/env, and using that will find PHP's location in the path much like 'which', but not requiring it. Also, the require is there to show him how to include the file in his example. Feb 24, 2013 at 20:36
  • 1
    I understand that but the original poster wanted a command-line solution. Also, I'm new to Unix but perhaps you meant to use /usr/bin/env? I tried Ubuntu and Mac OS X and neither has env in /bin, only /usr/bin. But you are correct, env php script.php should work, I just tested it as well. I cannot change my vote however; it is locked. Feb 25, 2013 at 3:05
2

Bash has a type command.

type -p php

will give you the location of the executable based on your $PATH.

You have spaces around your equal signs which Bash doesn't allow. This is what your command should look like:

PHP=$(type -p php) 

or you could even execute it directly:

$(type -p php) script.php
1

Try this:

if [ -e /usr/bin/php ]; then
0
0

whereis php locates it

2
  • The whereis command doesn't work for /usr/local/zend/bin/php ...not sure why, but it may be because it was installed from a tar.gz that just ran a crude bash install program Sep 4, 2010 at 9:06
  • whereis, if I remember right, will only look in your current PATH variable for the executable you are looking for. Most standard paths include /usr/bin /bin and if you are root: /usr/sbin and /sbin. Since in this case you have php in a special directory whereis likely won't find it unless you have a modified PATH variable. You can check by typing echo $PATH Sep 4, 2010 at 15:15
0

For short piece of code you can use: && and ||

[ -x /usr/bin/php ] && PHP=/usr/bin/php || PHP=/usr/local/zend/bin/php

BTW -x return true if the file is executable -e return true if the file exists

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.