怎样才能创建,然后在采购Bash脚本的功能使用别名? [英] How can one create and then use an alias in a function of a sourced Bash script?

查看:148
本文介绍了怎样才能创建,然后在采购Bash脚本的功能使用别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创造,然后在采购Bash脚本的功能使用的别名。我碰到盗梦空间般的困难,我想就如何做到这一点适当的AP preciate指针。

I want to create and then use an alias in a function of a sourced Bash script. I've run into Inception-like difficulties and I would appreciate pointers on how to do this properly.

下面是一个示例脚本来源:

Here's a sample script to source:

#!/bin/bash

myFunction(){
    alias zappo="echo"
    zappo
}

结果任何建议?

推荐答案

请注意,别名将有脚本的功能有限。从高级bash脚本编程指南

Note that aliases will have limited functionality for scripting. From the Advanced Bash Scripting Guide:

在一个脚本,别名具有非常有限的用处。这将是很好,如果别名可以承担一些中C preprocessor的功能,如宏扩展,但遗憾的是击不展开别名体内的论点。 [2]此外,脚本未能扩大复合结构,例如,如果/ then语句,循环和函数中的一个别名本身。另外一个限制是,别名不会递归扩展。几乎无一例外,无论我们想一个别名做可以用功能更有效地完成。

In a script, aliases have very limited usefulness. It would be nice if aliases could assume some of the functionality of the C preprocessor, such as macro expansion, but unfortunately Bash does not expand arguments within the alias body. [2] Moreover, a script fails to expand an alias itself within "compound constructs," such as if/then statements, loops, and functions. An added limitation is that an alias will not expand recursively. Almost invariably, whatever we would like an alias to do could be accomplished much more effectively with a function.

我会用一个变量是:

myFunction(){
    zappo="echo"
    $zappo "foo bar"
}

甚至是包装函数:

Or even a wrapper function:

zappo() {
    if [ $1 = 'some value'] ; then
        do something
    fi

    # apply out arguments to echo
    echo $@
}

现在这样称呼它:

zappo log_info "foo bar"

这篇关于怎样才能创建,然后在采购Bash脚本的功能使用别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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