I'm doing a bash script that has to run a php file. Usually it would be php file.php
, but the server I'm running this script has many versions of php installed (Plesk server, many projects, different versions for each one...)
So, for the command line there are some aliases:
alias php7='/opt/plesk/php/7.4/bin/php'
alias php='/opt/plesk/php/8.0/bin/php'
I have read that the best ways of finding an executable would be using type
or command -v
, but in this case it doesn't output the path of the executable:
$ type php
php is aliased to `/opt/plesk/php/8.0/bin/php'
$ command -v php
alias php='/opt/plesk/php/8.0/bin/php'
I need to find the path to the php
executable regardless if it is an alias, an actual executable or whatever. The problem is that right now, if I run php file.php
in my script I get this:
$ ./test
./test: line 9: php: command not found
Any help? Thanks!!
Update: this is the content of the script I’m doing:
#!/usr/bin/env bash
SCRIPT_DIR="$( pwd )"
CLI_FILE="${SCRIPT_DIR}/ofw/vendor/cli/cli.php"
PHP_FILE="$( which php )"
if test -f "$CLI_FILE"; then
php $CLI_FILE
else
echo "ERROR: OFW CLI must be run in a OFW project folder."
fi
CodePudding user response:
If ./test
is a shell script, note that your aliases are not available to it.
Unless you really ask it to:
shopt -s expand_aliases
source ~/.bashrc # or whatever file defines your aliases.
php file.php # should now work
However, a simpler method is to add the php directory to the PATH of the script
PATH=/opt/plesk/php/8.0/bin/php:$PATH
php file.php
The generic approach. This assumes the user's shell is bash.
setupTool() {
local tool=$1
if ! [[ $tool =~ ^[[:alnum:]._-] $ ]]; then
echo "Malicious input: '$tool'" >&2
return 1
fi
case "$( bash -ic "type -t $tool" )" in
alias)
shopt -s expand_aliases
eval "$( bash -ic "alias $tool" )"
;;
function)
eval "$( bash -ic "declare -f $tool" )"
;;
file|builtin|keyword)
: ;; # no-op
*) echo "error: don't know about $tool" >&1
return 1
;;
esac
}
setupTool php || exit 1
php file.php