3

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 https://github.com/fatso83/dotfiles/blob/$1; 
}

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.

  • Can you post ~/.bashrc and the alias file? – j-money Mar 5 '19 at 10:46
  • @j-money I linked to the whole setup in my github dotfiles repo. It is way to complex/involved to post here, as it consists of 3-4 intertwined files. I did get a correct answer, though. – oligofren Mar 5 '19 at 12:03
5

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!"
| improve this answer | |
  • 1
    That was exactly it. I edited your post and added the executable example I verified your answer with. – oligofren Mar 5 '19 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.