How can I use an alias in a function?
In my dotfiles I have some functions that rely on aliases or functions to exist for them to work. For some reason, I can get them to reference other functions I have created, but not aliases for commands. How do I fix this?
Example:
function open-dotfiles-commit(){ xopen
}If I have an alias xopen (alias xopen=xdg-open), the open-dotfiles-commit command will fail with xopen: cannot find command. On the other hand, if I replace the alias definition with a function called xopen (function xopen(){ xdg-open; };) it works!
I have even tried setting shopt -s expand_aliases in the same file as where I define the aliases - unsuccessfully. The alias and functions file is sourced by my .bashrc.
1 Answer
From the bash manual:
Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a command.
I'd bet that your aliases are defined after these functions are defined. Try defining the functions later.
For reference, I tested foo () { ll "$1"; }, using the ll alias from the default .bashrc, and it worked fine.
Runnable example:
def-before() { do-foo; };
alias do-foo="echo foo u!"
def-after() { do-foo; };
def-before
# prints "do-foo: Could not find command"
def-after
# prints "foo u!" 1