带有参数和自动完成功能的 bash 别名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3778065/
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-17 22:40:36  来源:igfitidea点击:

bash alias with argument and autocompletion

linuxbash

提问by Gadolin

I have a bunch of scripts in directory that exists on the path, so I can access each wherever I am. Sometime those are very simple util scripts that "vims" the file. From time to time I would like to quickly see the content of script file and see path to file the script opens (then make cat, grep ...).

我在路径上存在的目录中有一堆脚本,所以我可以随时随地访问每个脚本。有时,这些是非常简单的 util 脚本,可以“修改”文件。有时我想快速查看脚本文件的内容并查看脚本打开的文件路径(然后 make cat、grep ...)。

I would like to make an alias which will "cat" given script wherever I am.
Given one is not working:
alias a="cat `which \$1`"
If I place script name instead of parameter number($1) it works fine. But with parameter not.

我想创建一个别名,无论我在哪里,它都会“cat”给定的脚本。
鉴于一个不起作用:
alias a="cat `which \$1`"
如果我放置脚本名称而不是参数编号($ 1),它工作正常。但是没有参数。

The second question (I wish life be so so beautiful!) would be getting auto-completion of script name for that alias.
Using a script that could exist in my "bin" directory would another approach which I can take.

第二个问题(我希望生活如此美好!)将自动完成该别名的脚本名称。
使用可能存在于我的“bin”目录中的脚本是我可以采用的另一种方法。

采纳答案by Paused until further notice.

If your function is called "foo" then your completion function could look like this:

如果您的函数名为“foo”,那么您的完成函数可能如下所示:

If you have the Bash completion package installed:

如果您安装了 Bash 完成包:

_foo () { local cur; cur=$(_get_cword); COMPREPLY=( $( compgen -c -- $cur ) ); return 0; }

If you don't:

如果你没有:

_foo () { local cur; cur=${COMP_WORDS[$COMP_CWORD]}; COMPREPLY=( $( compgen -c -- $cur ) ); return 0; }

Then to enable it:

然后启用它:

complete -F _foo foo

The command compgen -cwill cause the completions to include all commands on your system.

该命令compgen -c将导致完成包括系统上的所有命令。

Your function "foo" could look like this:

您的函数“foo”可能如下所示:

foo () { cat $(type -P "$@"; }

which would catone or more files whose names are passed as arguments.

这将是cat一个或多个名称作为参数传递的文件。

回答by shodanex

For the alias with argument, use functioninstead of aliases :

对于带参数的别名,请使用function而不是 aliases :

a() { cat `which ` ;}

Or if you do it on more than one line, skip th semicolon :

或者,如果您在多行上执行此操作,请跳过分号:

a() {
    cat `which `
}

You can enter it interactively at the shell prompt :

您可以在 shell 提示符下以交互方式输入它:

shell:>a() {
>cat `which `
>}
shell:>