11

I'm trying to add a multi-word alias in my .bashrc. More specifically, I want apt update to be sudo apt update -y. But I can't figure out how to specify a multi-word alias. I've tried the following, but none of them have worked:

alias 'apt update'='sudo apt update -y'
alias "apt update"='sudo apt update -y'
alias apt\ update='sudo apt update -y'

Does someone know a way around this?

Thank you.

1 Answer 1

21

Well, I get:

$ alias 'apt update'='sudo apt update -y'
bash: alias: 'apt update': invalid alias name

which seems clear enough.

Similarly, you can't have functions or commands with whitespace in their names... or well, you could, but you'd have to escape the space when using them, not fun.

The simple workaround would be to use another name instead, e.g. this should work:

alias apt-update='sudo apt update -y'

Or if you really want to, you could make apt a function that checks the second word (first argument) too. This should turn apt update foo into sudo apt update -y foo, just like the alias would; and would run any other commands as they were:

apt() {
    if [ "$1" = "update" ]; then
        shift        # eat the 'update'
        sudo apt update -y "$@"
    else 
        command apt "$@"
    fi
}

(Of course apt update doesn't take arguments, but you might want to be able to pass them for some other similar ones.)

3
  • 2
    There is also (for fun, mainly) the ugly alias apt='sudo apt '; alias update='update -y', but the two aliases (taken individually) would likely be an unwanted side effect.
    – fra-san
    Commented Sep 28, 2021 at 12:50
  • 1
    @fra-san, yeah, the meaning changes, but it might not be that bad here. At least as long as update doesn't exist as a command on its own. Most uses of apt require privilege anyway, and sudoing something like apt search shouldn't be too dangerous.
    – ilkkachu
    Commented Sep 28, 2021 at 13:32
  • 2
    "Sudoing something like apt search shouldn't be too dangerous." Famous last words :) Don't use sudo if you don't need it just because it's convenient.
    – chepner
    Commented Sep 29, 2021 at 12:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .