Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias inside function [duplicate]

Tags:

alias

bash

sh

bash -c 'shopt -s expand_aliases

a() {
    alias myfunc="echo myfunc"
}

main() {
    a
    myfunc
}

main'

a function is used to alias some commands, which are used in main function.

Output:

environment: line 8: myfunc: command not found
like image 380
FH0 Avatar asked Oct 31 '25 22:10

FH0


1 Answers

This is expected behavior, explained in the manual as follows:

Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a command.

In this case that means myfunc in main is not going to be expanded to echo myfunc unless your script calls a to define it above the definition of main.

The shell does not execute commands inside a function definition until that function is called. So, defining a above main doesn't make any difference; myfunc isn't defined until a is called.

Compare these two:

$ bash -O expand_aliases -c '
foo() { bar; }
alias bar=uname
foo'
environment: line 1: bar: command not found
$ bash -O expand_aliases -c '
alias bar=uname
foo() { bar; }
foo'
Linux

The workaround is to avoid using aliases in shell scripts. Functions are way better.

like image 185
oguz ismail Avatar answered Nov 02 '25 14:11

oguz ismail