How can one create and then use an alias in a func

2019-08-29 07:14发布

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条回答
唯我独甜
2楼-- · 2019-08-29 07:36

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"
查看更多
登录 后发表回答