Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I want to be able to run a command, it fails cause it doesn't have proper permissions. Then I can write "please" to sudo the command I just ran.

Here's what I want to do in the terminal:

$ run command
"you don't have access to do that"
$ please
"ran successfully"

I saw that !! will grab the previous command, so I thought I could use that, but I can't get it to work.

my please.sh shell script looks like this, but I can't get any of these to work. It just says "command not found !!" and prints out the sudo usage.

#!/bin/zsh

#sudo !!
#sudo `!!`
sudo $(!!)
share|improve this question
    
Does it work without the script? If you just run sudo !! does it run as expected? I think !! may just be a bash alias, so it may not work in zsh –  Chris Wayne Jul 19 '12 at 1:07
3  
AFAIK, history expansion (!! and others) only works in interactive shells and not in scripts. –  Thor Jul 19 '12 at 1:16
    
sudo !! in interactive mode almost works as expected. when I pressed enter it would replace !! with the previous command. then i had to press enter again to run it. –  jb. Jul 19 '12 at 2:53
add comment

1 Answer 1

up vote 4 down vote accepted

You cannot use !! in a shell script, as you cannot access the parent shell in a child shell. Though I recommend using sudo !!, if you really want to make a BASH script, you would have to use .bash_history, like so:

#!/bin/bash
sudo `cat $HOME/.bash_history | tail -n1`

It is definitely NOT a perfect solution, but it should do the trick. If you are using ZSH, this will not work, as ZSH does not output to .bash_history (of my knowledge). UPDATE: Here is a version that should work with ZSH:

#!/usr/bin/zsh
. $HOME/.zshrc
sudo `cat \`readlink -f $HISTFILE\` | tail -n1`

Hope this helps!

If you don't understand the script, it simply runs the last command entered in BASH with sudo.

share|improve this answer
    
ok. I'm using zsh though. is there any equivalent for .bash_history in zsh? –  jb. Jul 19 '12 at 2:51
    
Now that I look, yes, there is a version that should work. I haven't tested it yet though. –  MiJyn Jul 19 '12 at 23:45
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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