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

link|improve this question

40% accept rate
4  
Wrap it in a function and add it to .bashrc. Problem solved. – Daniel Beck Jan 1 at 9:10
feedback

2 Answers

up vote 2 down vote accepted

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.

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

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.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.