Bash alias with a space as a part of the command
Yes, you will need to use a function. An alias would work if you wanted to add a parameter, any arguments given to aliases are passed as arguments to the aliased program but as separate parameters, not simply appended to what is there. To illustrate:
$ alias foo='echo bar'
$ foo
bar
$ foo baz
bar baz
As you can see, what was echoed was bar baz
and not barbaz
. Since you want to concatenate the value you pass to the existing parameter, you'll need something like:
function com(){ sudo openvpn --config /path/to/my/openvpn/configs/"$@"; }
Add the line above to your ~/.bashrc
and you're ready to go.
Related videos on Youtube
boolean.is.null
Updated on September 18, 2022Comments
-
boolean.is.null over 1 year
I'm trying to create a bash alias, where the alias itself has a space in it.
The idea is that the alias (i.e.
con
) stands forsudo openvpn --config /path/to/my/openvpn/configs/
. Which results in a readable command, when thecon
alias is used.i.e:
`con uk.conf` == `sudo openvpn --config /path/to/my/openvpn/configs/uk.conf`
I understand that I can't declare the alias like this:
con ="sudo openvpn --config /path/to/my/openvpn/configs/"
. Would bash functions work in this scenario? I've never heard of that, but when researching a solution for this minor issue. -
Toby Speight over 8 yearsYou can use
"$@"
instead of"$1"
so that subsequent arguments are passed through, too. (General comment, possibly irrelevant to the specific case here) -
terdon over 8 years@TobySpeight D'oh! I should have thought of that. Thanks, edited.
-
TMH over 8 years@TobySpeight just for clarification, does that mean
com uk.conf -something else
would translate tosudo openvpn --config /path/to/my/openvpn/configs/uk.conf -something else
? -
terdon over 8 years@TomHart yes.
$@
contains all parameters given. See What is the difference between $* and $@?.