How can one create and then use an alias in a function of a sourced Bash script?

ぃ、小莉子 提交于 2019-12-13 04:32:20

问题


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
}


Any suggestion?


回答1:


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

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.

I would use a variable for this:

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 $@
}

now call it like this:

zappo log_info "foo bar"


来源:https://stackoverflow.com/questions/17568366/how-can-one-create-and-then-use-an-alias-in-a-function-of-a-sourced-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!