为什么要创建一个别名来创建函数? [英] Why would I create an alias which creates a function?

查看:96
本文介绍了为什么要创建一个别名来创建函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶尔会看到这种模式,尤其是在有关Bash提示自定义的问题中。

I see this pattern every once in a while, especially in questions about Bash prompt customization.

alias f='_ () { useful code; }; _'

我完全没有理由在此处创建别名。显而易见的重构

I can see no reason at all to create an alias here. The obvious refactoring

f () { useful code; }

这样就避免了完全声明别名,而只是一劳永逸地定义了函数,看起来更简单,更易于理解,更不易碎且效率更高。 (以防万一,每次调用别名时,别名最终都会重新声明该函数。)

which avoids declaring an alias altogether, and simply defines the function once and for all, seems simpler, more understandable, less brittle, and more efficient. (In case it's not obvious, the alias ends up redeclaring the function every time you invoke the alias.)

例如,制作带有参数的Bash别名?有几个答案可以证明这种技术。 使用ftp路径运行lftp的bash脚本是一个问题,该问题中的代码与函数内部的实际功能有关,并且OP并没有解释为什么即使我轻描淡写也是如此。

For example, Make a Bash alias that takes a parameter? has several answers which exhibit this technique. bash script to run lftp with ftp path is a question which has code like this in a question about the actual functionality inside the function, and the OP doesn't explain why even though I prodded gently.

这是否纯粹是反模式,还是有这样做的实际原因?在什么情况下这种设计有意义?

Is this just plainly an antipattern, or is there an actual reason to do this? Under what circumstances would this design make sense?

这不是别名,后面是空格,还是代码混淆(示例I除了这种神秘的技术,我们发现它通常是完全可读的。)

This is not about aliases with a space after them, or about code obfuscation (the examples I have found are generally entirely readable, apart from this mystifying technique).

推荐答案

我发现了这个 [ U& L]在Bash中,何时使用别名,何时编写脚本以及何时编写函数? 解释了在别名中定义函数的好处。

I found this answer too [U&L] In Bash, when to alias, when to script, and when to write a function? which explains the benefit of defining a function in an alias.


这样做比声明一个函数的好处是您的别名
不能简单地被源代码覆盖(或使用覆盖)。 / code>)一个脚本,其中
恰好声明了一个同名的函数。

The benefit of doing so over declaring a function is that your alias cannot be simply overwritten by source-ing (or using .) a script which happens to declare a same-named function.

这篇关于为什么要创建一个别名来创建函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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