How to pass alias through sudo
A very elegant solution can be found in the Archlinux-Wiki:
alias sudo='sudo '
# whitespace ---^
works to pass all aliases to sudo
.
Source: http://wiki.archlinux.org/index.php/Sudo#Passing_aliases
I'm not real clear on what you're trying to do. I can see two ways:
The Right Way
alias pd='sudo perl -Ilib -I/home/myuser/lib -d'
Then executing pd ./mytool
will execute your debugging command as root but still preserve the benefits of sudo (audit trail, not operating out of a root shell).
Example:
insyte$ alias sid='sudo id' insyte$ sid uid=0(root) gid=0(root) groups=0(root)
The Easy Way
Add the aliases to root's .bashrc
and use sudo -i
whenever you sudo to root.
root# echo 'alias fb="echo foo bar"' >> /root/.bashrc root# exit exit insyte$ sudo -i root# fb foo bar
Just have two aliases and use a variable
I don't see the reason for using awk
or cut
unless it's to only have the core alias defined once in order to make it easier to modify. If that's the case, then this works:
# ... in .bashrc ...
pd='perl -Ilib -I/home/myuser/lib -d'
alias pd="$pd"
alias spd="sudo $pd"
Here's a simplistic function to make alias pairs such as the one above:
mkap () {
alias $1=$2
alias s$1="sudo $2"
}
To use:
mkap pd 'perl -Ilib -I/home/myuser/lib -d'
mkap ct 'cat'
Now you have pd
and spd
plus ct
and sct
.
$ ct /etc/shadow
cat: /etc/shadow: Permission denied
$ sct /etc/shadow
[sudo] password for dennis:
root:[censored]...
$ alias
alias ct='cat'
alias pd='perl -Ilib -I/home/myuser/lib -d'
alias sct='sudo cat'
alias spd='sudo perl -Ilib -I/home/myuser/lib -d'
I wish I could mark two answers as "correct". Combining the Right Way from Insyte's, um, insightful post, with the awk (or cut) solution from Bill Weiss, I've come up with this:
alias spd="sudo $(alias pd | cut -d\' -f2)"
Now I'll just go and put this into a shell function in my .bashrc or something, and then create "s" versions of all my aliases that I desire to run as root.
Update: slight modification of Dennis Williamson's simplistic function to make it a bit easier to use:
salias()
{
local a c
a=$(echo "$1" | cut -f1 -d=)
c=$(echo "$1" | cut -f2- -d=)
alias $a="$c"
alias s$a="sudo $c"
}
This means I just have to put "s" in front of the entire command. Instead of:
alias pd='perl -Ilib -I/home/myuser/lib -d'
I just add the s in the front.
salias pd='perl -Ilib -I/home/myuser/lib -d'
And I'm done. Sure, the computer does a bit more work, but that's what a computer is for. :-)
Thanks!