Bash alias with a space as a part of the command

16,021

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.

Share:
16,021

Related videos on Youtube

boolean.is.null
Author by

boolean.is.null

Updated on September 18, 2022

Comments

  • boolean.is.null
    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 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.

  • Toby Speight
    Toby Speight over 8 years
    You can use "$@" instead of "$1" so that subsequent arguments are passed through, too. (General comment, possibly irrelevant to the specific case here)
  • terdon
    terdon over 8 years
    @TobySpeight D'oh! I should have thought of that. Thanks, edited.
  • TMH
    TMH over 8 years
    @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?
  • terdon
    terdon over 8 years
    @TomHart yes. $@ contains all parameters given. See What is the difference between $* and $@?.