简体   繁体   English

在 bash 命令中间使用别名

[英]Using alias in the middle of bash command

Is it possible to substitute an alias in the middle of the command.是否可以在命令中间替换别名。 for eg If suppose I have an alias例如,如果假设我有一个别名

alias get_pods= 'kubectl get pods -n mynamespace'

This works perfectly fine when I do "get_pods" from bash command line.当我从 bash 命令行执行“get_pods”时,这非常有效。

As namespace is needed as a suffix in almost all the commands, is it possible that I have my namespace as an alias.由于几乎所有命令都需要命名空间作为后缀,所以我有可能将命名空间作为别名。 For eg例如

alias  myname=' -n mynamespace'

and then I use it in my command line然后我在命令行中使用它

kubectl get pods 'myname'

In this way, I can create multiple aliases for different namespaces and just change the suffix at the end of my shell command.这样,我可以为不同的命名空间创建多个别名,只需更改 shell 命令末尾的后缀即可。

Basically, all I want to do is to substitute the alias in my bash command and execute it.基本上,我要做的就是在我的 bash 命令中替换别名并执行它。

UPDATE更新

I tried adding "`" symbol but it is not working我尝试添加“`”符号但它不起作用

kubectl get pods `myname`

-n: command not found
No resources found in default namespace.

You can use a function like this:您可以像这样使用 function:

function myname() {
  "$@" -n mynamespace
}

The "$@" means "insert all arguments here". "$@"表示“在此处插入所有 arguments”。 The double-quotes ensures that they are word-split correctly.双引号确保它们被正确地分词。 Then you'd invoke it using然后你会调用它使用

myname kubectl get pods

Syntax is a bit different but the behavior is the same.语法有点不同,但行为是一样的。 You could probably work something else out if you really wanted to use the syntax you want, but it would be more complicated.如果您真的想使用您想要的语法,您可能可以解决其他问题,但这会更复杂。

Probably simpler would be to define a variable like this:可能更简单的是定义一个像这样的变量:

export myname="-n mynamespace"

and execute it using并使用执行它

kubectl get pods $myname

Just store the data in an array.只需将数据存储在数组中。

myname=(-n mynamespace)

kubectl get pods "${myname[@]}"

Use a variable instead of an alias.使用变量而不是别名。

myname='-n mynamespace'
kubectl get pods $myname

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

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