bash 如何在 bashrc 中创建一个函数来接受参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15206771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:44:23  来源:igfitidea点击:

How to create a function in bashrc to accept arguments?

functionterminalosx-mountain-lionbash

提问by CommonCents

I would like to have an alias in my bashrc file to append the argument passed to it from terminal. For example:

我想在我的 bashrc 文件中有一个别名来附加从终端传递给它的参数。例如:

$ lh300

calls:

调用:

alias lh3000='open http://localhost:3000'

However, if I type:

但是,如果我输入:

$ lh8080 or lh followed by any number:

$ lh8080 或 lh 后跟任意数字:

$ lh#### 

I would like to call a function that appends the #### into an alias that will

我想调用一个函数,将 #### 附加到一个别名中,该别名将

'open http://localhost:####'

How can I do this?

我怎样才能做到这一点?

回答by chrisaycock

You won't be able to use an alias, but you can create a function:

您将无法使用别名,但您可以创建一个函数:

lh() { open http://localhost:; }

Then just call it like lh 3000.

然后就这样称呼它lh 3000

回答by chepner

A questionable hack involving command_not_found_handle:

一个可疑的黑客涉及command_not_found_handle

command_not_found_handle () {
    if [[  =~ lh([[:digit:]]+) ]]; then
        open "http://localhost:$BASH_REMATCH[1]"
    fi
}

This requires bash4 or later, I believe.

bash我相信这需要4 个或更高版本。