MacOS – Using ‘alias’ in bash script in OSX

aliasbashmacos

I write some scripting and I want to make it work on Linux and Mac. The problem is, that "Implementations of sed, readlink, zcat, etc. are different on OS X and Linux."

So I tried THIS approach, but for me alias command does not work as I expect.
Here is simple script 'a':

$cat a
alias readlink=gredlink
readlink --help

and the result …

$./a
readlink: illegal option -- -
usage: readlink [-n] [file ...]

Could anyone explain me what's under the curtain, and is there workaround?

Using OSX Yosemite 10.10.5
It's the same with the bash included with the OS as well with "GNU bash, version 4.3.42(1)-release (x86_64-apple-darwin14.5.0)"

Best Answer

Aliases aren't interpreted within shell scripts. From bash(1):

Aliases are not expanded when the shell is not interactive, unless the expand_aliases
shell option is set using shopt)

So the script still calls the standard readlink which doesn't know about --help.

Instead of setting expand_aliases (which you have to remember to do so on each system and which may lead to unexpected side-effects in other scripts) I would recommend to use functions instead:

function my_readlink() {
    greadlink "$@"
}
my_readlink --help