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 for sudo openvpn --config /path/to/my/openvpn/configs/. Which results in a readable command, when the con 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.


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
$ 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.

  • 4
    You can use "$@" instead of "$1" so that subsequent arguments are passed through, too. (General comment, possibly irrelevant to the specific case here) – Toby Speight Dec 3 '15 at 15:27
  • @TobySpeight D'oh! I should have thought of that. Thanks, edited. – terdon Dec 3 '15 at 15:39
  • 1
    @TobySpeight just for clarification, does that mean com uk.conf -something else would translate to sudo openvpn --config /path/to/my/openvpn/configs/uk.conf -something else? – TMH Dec 3 '15 at 15:51
  • 4
    @TomHart yes. $@ contains all parameters given. See What is the difference between $* and $@?. – terdon Dec 3 '15 at 15:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.