I was wondering if you could alias a command, and use it in the same line of code, see this example:
alias php=/opt/plesk/php/5.6/bin/php; php -v;
I want this to output PHP 5.6.
alias php=/opt/plesk/php/7.3/bin/php; php -v;
and I want this to output PHP 7.3. However, what I get is this:
php -v
# outputs 5.6
alias php=/opt/plesk/php/5.6/bin/php; php -v;
# outputs 5.6
alias php=/opt/plesk/php/7.3/bin/php; php -v;
# outputs 5.6
php -v
# outputs 7.3
I’ve tried the &&
operator but it has the same outcome.
I’m wanting to use this in a gitlab continuous integration script, which executes a script through ssh -t
by passing a string. However I am calling several php functions and I dont want to paste the full php path every time:
ssh -v -tt $SSH_HOST_NAME "__my_php_commands_here__"
3
Answers
I've went with a
.bashrc
solution. I initially started with this but for some reason the aliases werent being picked up. It appears you need to set a customexpand_aliases
setting.My .bashrc ended up looking like this:
This seemed to do the trick and gave me the correct PHP version while using
ssh [email protected] "php -v"
.I think the command line is being parsed, and aliases applied, before anything is executed. However, you can do it with shell functions. I don’t have PHP, but I have several Perl versions to test with:
So defining the pass-through function
changes how the word
perl
is interpreted later in the command line. Note that you do need the;
before}
— see this answer.For your use case, I would recommend using a different name to avoid confusion. E.g.:
Batch non-interactive shells don’t support aliases (by default). And that’s a good think.
alias
should be just used as your own, custom shorthand, not in batch scrips.You could
a) define a function with the same name and use full path for command resolution:
Downsides: function are not exported, unless you add
export -f php
, it is a shell function. Something likexargs php
will work incorrectly.b) use a varaible.
Downside: you have to modify all scripts and always check out for the
$php
.c) Modify the path, so your php is found first. You could create a temporary directory and add it to path:
If you
export PATH
correctly, it will work everywhere. Remember to remove the folder tho.Side note: You don’t “alias a variable”, you “alias a command”.
alias
allows you to substitute the first (and only the first) word in a simple command.php
is a command.