5

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)"

1 Answer 1

5

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
2
  • Well this explains some quirks, but that does not work for me too for some reason. shopt | grep alias returns expand_aliases on but again does not use the alias :-( Commented Apr 26, 2016 at 8:41
  • But ... if calling shopt -s expand_aliases inside the script after alias command works !! Thanks :) Commented Apr 26, 2016 at 8:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .