Linux – How to create alias that takes a positional argument in Linux bash

bashcommand linelinux

Lets say I have a bash command with a couple of options and the variable that I am interested in (e.g. filename):

my_cmd option1 option2 filename

I created an alias:

alias my_cmd_12="my_cmd option1 option2"

this allows me to remove typing all of the options. However there are some flags coming after the variable I am interested (e.g. filename):

my_cmd option1 option2 filename --flag1

How do I create an alias that takes all option an flags:

my_alias filename is equivalent to

my_cmd option1 option2 filename --flag1

Best Answer

You can't do this with alias. Alias works by replacing string with another string. With this alias defined

alias my_cmd_12="my_cmd option1 option2"

my_cmd_12 filename --flag1 will expand to

my_cmd option1 option2 filename --flag1

But you want to invoke my_alias filename to get the same result. There is no way to replace my_alias with another string so --flag1 appears at the end.

However a function should work:

my_function() { my_cmd option1 option2 "$1" --flag1; }

Note this is just a minimal solution tailored to your example. In general you can use more positional parameters or "$@", conditional statements etc., according to what exactly you need. Functions are way more flexible than aliases.

More information here: In Bash, when to alias, when to script, and when to write a function?

Related Question