brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: alias sudo='sudo ' with a trailing space lets your aliases work after sudo

Linux
~/tips/tip-bash-alias-sudo-trailing-space

alias sudo='sudo '

Makes sudo ll and other aliases after sudo work instead of giving command not found.

You made an alias, say ll for ls -lah. It works fine until you type sudo ll and get “command not found”. That looks like a bug, but bash is following its own rules here, and one space fixes it.

Bash only checks the first word of a command for an alias. In sudo ll, the first word is sudo, so ll goes to sudo untouched, and sudo has never heard of it. The bash manual has a small exception: if an alias value ends with a blank, bash also checks the next word for an alias. So you make sudo an alias of itself, with a space at the end:

alias sudo='sudo '

Put it in ~/.bashrc next to your other aliases. Now this works:

alias ll='ls -lah'
alias sudo='sudo '
sudo ll /var/log

Bash expands sudo to sudo , sees the trailing space, expands ll to ls -lah, and sudo receives a real command. The same trick works for other commands that take a command as their argument, like alias watch='watch ' so watch ll works too.

The caveat is that it only works for aliases. Shell functions in your .bashrc still won’t work after sudo, because sudo starts a new program and that program knows nothing about your shell’s functions. It also does nothing for an option between the two words: in sudo -u www-data ll the word after the alias is -u, so ll isn’t expanded. And aliases are only expanded in interactive shells by default, so none of this applies inside a script. For anything you need in scripts too, I’d write a small script in /usr/local/bin instead.

Further reading: Aliases (GNU Bash manual), bash(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link