8

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/"`?

Jayen
  • 522

2 Answers2

11

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.

3

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.

grawity
  • 501,077