Using sudo with an alias

Typically sudo will ignore any aliased commands from your .bashrc, .bash_aliases, or the alias command. For example, I use "ll" as an alias for "ls -lh". Typing "ll" will give me a long-listing of a directory's contents, while typing "sudo ll" will give me:

?
sudo : ll: command not found

I learned this when I tried to create an alias for "shutdown" that would refuse to shutdown if rtorrent was running. Unfortunately you need root privileges to use /sbin/shutdown, and sudo would completely ignore the clever script I aliased as "shutdown". The solution is an additional alias:

?
alias sudo = 'sudo '

The space following "sudo" tells bash to check if the command that follows the space is also an alias. From the bash man page:

?
man bash
 
...
If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion.
...

Now my aliased shutdown script is called even though it's being run with sudo. I've heard of another solution (also an alias), but I haven't tried it (1) because this one works just fine, and (2) because I don't understand why it works (if it does work). Here it is:

?
alias sudo = 'A=`alias` sudo  '

I'm not sure if it's just the hard way of doing things, or if it's somehow better, worse, or different.

Here's a copy of my current .bash_aliases file. This is a fresh install, so I'll probably add a lot to it in the future.

?
# Shortcuts
alias ll= 'ls -lh'
alias la= 'ls -lhA'
alias l= 'ls'
alias c= 'clear'
alias x= 'exit'
alias q= 'exit'
 
# Don't run shutdown if rtorrent is running - as long as there's a screen with "tor" in its name, shutdown won't run (unless you call /sbin/shutdown, or unalias it)
alias shutdown = '/home/james/scripts/safe.shutdown.sh'
 
# When using sudo, use alias expansion (otherwise sudo ignores your aliases)
alias sudo = 'sudo '

http://www.shellperson.net/using-sudo-with-an-alias/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值