shell issue: alias doesn't expand

342 views Asked by At

I have the following problem: I have many test scripts that are currently running using MKS Toolkit. We managed to run those scripts using the mingw shell (msys) but there are other scripts that make use of some aliases that are built-in MKS Toolkit and not in bash.

The problem is that nobody wants to change those scripts, not even automatically by using a script. This means that I should define and use those aliases. I tried defining the aliases in the "/etc/profile" file of msys shell but without any success. I also tried to use shopt -s expand_aliases (in "/etc/profile") but that doesn't work either.

Could someone share an idea on how this could be done. Mind that the existing scripts will have to remain the same.

Any thoughts or ideas are welcome.

Thanks

2

There are 2 answers

0
INS On BEST ANSWER

This answer gave me the solution. It involves defining the variable BASH_ENV before executing

bash script_name.sh

BASH_ENV will point to a script which sets the environment of the shell. In my case, to export the aliases and also the functions needed the script looks like this:

shopt -s expand_aliases

alias my_alias="echo my_alias"

function MyFunction {
    echo "MyFunction(DUMB):" $* 
}

export -f MyFunction
1
FatalError On

The /etc/profile is only sourced for login shells. If you want the aliases in your script, you should put them in a separate file and source them into the script(s) that need them. For example:

aliases.sh:

alias walrus="echo coo coo cah joo"

script.sh:

#!/bin/bash

shopt -s expand_aliases
. aliases.sh

walrus

and then

$ ./script.sh
coo coo cah joo

That's probably the most reasonable way to do it. If you insist on not changing the scripts at all, then you might be able to get away with executing them indirectly like:

bash --rcfile aliases.sh -i script.sh

That will tell bash to execute an interactive shell (and thus expand aliases and source our aliases script before executing script.sh).