jcubic
jcubic

Reputation: 66590

How to create alias for bash inside php exec?

I have code like this:

public function shell($code) {
    $code = preg_replace('/"/', '\\"', $code);
    exec('bash -c "' . $code . '"', $result);
    return $result;
}

and I want to add alias ls="ls --color=always". I've try to put it in .bashrc file that I've created just for that shell in my project directory and use:

exec('bash -c ". .bashrc;' . $code . '"', $result);

but this don't work, I'm in correct directory because I see that file when I call ls -A.

I've also try --init-file and --rcfile with just a file and full path.

How can I add aliases and functions to that shell? Is it possible?

Upvotes: 2

Views: 3540

Answers (2)

Michael Kropat
Michael Kropat

Reputation: 15227

Using functions is probably a better choice anyway. However, note that it is possible to use aliases if you set the expand_aliases option:

<?php
$code = 'ls';
$aliases = '
    shopt -s expand_aliases
    alias ls="ls -l"';
$code = $aliases . "\n" . $code;
exec('bash -c ' . escapeshellarg($code), $result);
echo implode("\n", $result) . "\n";

Output:

$ php aliasexec.php 
total 12
-rw-rw-rw- 1 mlk mlk 198 Feb 18 11:18 aliasexec.php

This is what the man page has to say (emphasis mine):

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt […].

The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. […] To be safe, always put alias definitions on a separate line, and do not use alias in compound commands.

For almost every purpose, aliases are superseded by shell functions.

That is why you must use newlines and not the ; character to define the alias.

Upvotes: 2

jcubic
jcubic

Reputation: 66590

The only thing that work is to add functions instead of aliases:

function ls() {
    /bin/ls --color=always $@;
}
function grep() {
    /bin/grep --color=always $@;
}

Upvotes: 0

Related Questions