Sunday, April 28, 2024
6
rated 0 times [  6] [ 0]  / answers: 1 / hits: 10325  / 3 Years ago, tue, july 27, 2021, 5:46:33

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 $(!!)

More From » command-line

 Answers
2

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.


[#36755] Thursday, July 29, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
otputler

Total Points: 53
Total Questions: 105
Total Answers: 93

Location: Zimbabwe
Member since Wed, Nov 9, 2022
2 Years ago
otputler questions
Tue, Aug 23, 22, 14:36, 2 Years ago
Fri, Jul 23, 21, 11:57, 3 Years ago
Sun, Feb 12, 23, 18:37, 1 Year ago
;