内部别名 [英] Alias inside function

查看:60
本文介绍了内部别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bash -c 'shopt -s expand_aliases

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

main() {
    a
    myfunc
}

main'

a 函数用于别名某些命令,这些命令在 main 函数中使用.

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

输出:

environment: line 8: myfunc: command not found

推荐答案

这是预期的行为,在

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.

在这种情况下,这意味着 main 中的 myfunc 不会扩展为 echo myfunc ,除非您的脚本调用 a 定义它,使其超出 main 的定义.

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.

我敢肯定,在调用该函数之前,shell不会在函数定义内执行命令.因此,在 main 上方定义 a 并没有任何区别;在调用 a 之前,未定义 myfunc .

I'm sure it is clear to all that 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.

比较这两个:

$ 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

解决方法是避免在Shell脚本中使用别名.功能更好.

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

这篇关于内部别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆