简体   繁体   English

在 bash 脚本别名中使用函数参数

[英]Using function parameters in a bash script alias

I have a bash script that I want to add an alias to that utilizes some function parameters.我有一个 bash 脚本,我想为其添加一个别名,该脚本使用一些函数参数。 However for some reason the command is not working when I use passed parameters.但是,由于某种原因,当我使用传递的参数时,该命令不起作用。

My alias:我的别名:

alias pa='_pa() { php artisan "$1" "$2" "$3" "$4" "$5"; }; _pa'

Which should be able to consolidate php artisan cache:clear down to pa cache:clear哪个应该可以合并php artisan cache:clearpa cache:clear

However this give me an input prompt, and not the expected command: php artisan cache:clear但是,这给了我一个输入提示,而不是预期的命令: php artisan cache:clear

Why am I unable to make an alias using this function?为什么我无法使用此功能创建别名?

Why are you doing that?你为什么这样做? Just change the alias to:只需将别名更改为:

alias pa='php artisan'

Or throw away the alias altogether, and just use a function?或者完全扔掉别名,只使用一个函数?

pa() {
  php artisan "$@"
}

Using "$@" will expand to as many arguments as you sent to pa使用"$@"将扩展到与您发送给pa一样多的参数

An alias does not take parameters.别名不带参数。 If you have an alias foo and write如果你有一个别名foo并写

foo x y z

the shell simply expands foo to what ever you have defined, so if for instance shell 只是将foo扩展到您定义的任何内容,例如,如果

alias foo='bar baz'

, the above line would be turned into ,上面的行将变成

bar baz x y z

That's why it's called alias expansion and not alias invocation in the man page.这就是为什么它在手册页中被称为别名扩展而不是别名调用

Further, your alias pa is pretty pointless.此外,您的别名pa毫无意义。 It does not do anything else than defining a function named _pa and then invoke it.除了定义一个名为 _pa 的函数然后调用它之外,它什么都不做。 Therefore, if in your shell no function of this name has been defined before, doing a因此,如果在您的 shell 中之前没有定义过此名称的函数,请执行

pa 10 20 30 40 50

is expanded to扩展为

_pa() { 
     php artisan "$1" "$2" "$3" "$4" "$5"
}
_pa 10 20 30 40 50

and thus causes the function _pa to spring into existence and also invoke this function.从而导致函数 _pa 出现并调用这个函数。 As we have alias expansion, those remaining parameters (10, 20,...) are appended to the line and end up as parameter to the function _pa.由于我们有别名扩展,那些剩余的参数 (10, 20,...) 被附加到该行并最终作为函数 _pa 的参数。

Basically, with every repeated use of your alias pa , you throw away the old _pa and create it freshly.基本上,每次重复使用别名pa ,您都会丢弃旧的_pa并重新创建它。 It is not forbidden to do this, but a cleaner solution would be to define the function separately, and if you want to have a second name for this function for whatever reason, define the alias after:不禁止这样做,但更简洁的解决方案是单独定义函数,如果您出于任何原因想要为该函数使用第二个名称,请在以下定义别名:

_pa() { 
     php artisan "$1" "$2" "$3" "$4" "$5"
}
alias pa=_pa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM