4

I recently switched from tcsh to bash, and I'm used to being able to do things like sudo `alias netstat` but since alias gives name=value in bash, I can't do this anymore. Is there an equivalent in bash, so I don't have to do sudo `alias netstat | sed -r "s/.*='(.*)'/\1/"`?

  • 4
    Wrap it in a function and add it to .bashrc. Problem solved. – Daniel Beck Jan 1 '12 at 9:10
2

You're trying to have bash expand aliases after sudo. You do not need to do it the exact same way; in fact, there is a far more convenient way in bash – add an alias for sudo that ends with a space...

alias sudo="sudo "

...and sudo netstat will be expanded automatically.

| improve this answer | |
  • excellent, and sudo \netstat won't expand netstat's alias! – Jayen Jan 1 '12 at 13:41
7

Bash stores its list of aliases in the associative array BASH_ALIASES. The equivalent of sudo `alias netstat` is then sudo ${BASH_ALIASES[netstat]}. However, I would suggest the following instead, which works with builtin shell commands and deals correctly with quoting:

sudo bash -c "${BASH_ALIASES[netstat]}"

There's still a lot that won't work with this, like e.g. nested aliases.

| improve this answer | |

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.