bash - 将别名命令转换为完整格式
Tianye
・4 分钟阅读
问题
我正在使用Ubuntu终端来管理我的工作。我创建了一些别名,帮助我更快地完成工作。
例如:
$ alias kprod="kubectl --namespace=hello"
然后按如下方式使用:
$ kprod get pods
我的主要任务之一是,找到我的应用程序何时可以在云上运行,所以,我调用此代码:
$ kprod get pods | grep APPNAME
但是我需要再一次运行它直到它准备好,我想使用watch
命令简化这个任务,不幸的是,因为kprod是别名,所以没法工作。
$ watch kprod get pods
sh: 1: kprod: not found
我的问题:
- 是否可以用
watch
shell命令解决这个特定的问题? 例如:
$ kprod get pods | TRANSLATE kubectl --namespace=hello get pods
它使它与
watch
和其他应用程序?更新
使用
type
命令类似但不同,正如我所尝试的那样,不可能给它一个完整的表达式,并且"翻译"它,因为它试图单独转换表达式的每个标记。因为pod (在上面的例子中)不是别名字符串。例如:
$ type kprod get pods kprod is aliased to `kubectl --namespace=hello' -bash: type: get: not found -bash: type: pods: not found
是,我可以使用
type
命令手动执行它,但是,它是手动的,我在寻找自动化方式。
回答1
别名作为终端中的快捷方式,它不是相反的方式。
bash脚本kprod
的内容
#!/bin/bash
kubectl --namespace=hello $@
命令末尾的$@会扩展到你在命令行上传递的所有参数。
将此脚本放置在路径中的文件夹中,这样,只需输入名称即可运行脚本。虽然设置起来比较困难,但是,同样容易使用作为你的别名,此外,你还可以在自动化中使用它。
回答2
是,可以制作名为watch_alias 的小脚本,它会展开别名,然后会展开的命令传递给watch ,以~/bin/watch_alias
格式保存以下内容,并且使它成为可执行的(chmod a+x ~/bin/watch_alias
):
#!/bin/bash
## enable alias expansion in scripts
shopt -s expand_aliases
## source the .bashrc file where your aliases should be
. ~/.bashrc
## The first argument of the script is the alias
aliasCom=$1
## Remove the 1st argument from the $@ array (the script's arguments)
shift
## Parse the output of type to get what the real command is
realCom=$(type $aliasCom | grep -oP"`K.[^']+")
## watch the unaliased command
watch $realCom"$@"
然后,你可以运行这个命令而不是watch :
watch_alias kprod get pods