Using alias in the middle of bash command

Is it possible to substitute an alias in the middle of the command. for e.g. 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.

As namespace is needed as a suffix in almost all the commands, is it possible that I have my namespace as an alias. For e.g.

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.

Basically, all I want to do is to substitute the alias in my bash command and execute it.

UPDATE

I tried adding "`" symbol but it is not working

kubectl get pods `myname`
-n: command not found
No resources found in default namespace.
6

3 Answers

You can use a function like this:

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

The "$@" means "insert all arguments here". 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
1

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
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like