0

I'm somewhat new to shellscripting. I am attempting to make a shellscript that when exececuted, will execute the second to last and the last executed commands in my terminal in that order. If I go to my terminal and type !! the last command will be executed. Similarly, if I type !-2 the second-to-last command will be executed. I am effectively trying to make a shellscript that when executed will perform the equivalent of me typing !-2 into my terminal twice in succession. I've tried numerous ideas (echo !-2, !-2, etc.) and honestly can't figure out how to get this to work. Can anyone give me any pointers?

  • Does this answer your question? https://unix.stackexchange.com/a/5701/411962 – fuzzydrawrings Feb 17 '22 at 06:37
  • 1
    You want to execute the second to last command, in what shell's history? Should this work even when called from e.g. a cron job? – Kusalananda Feb 17 '22 at 06:54
  • 2
    You probably want to do this as a function, not as a script. A script runs in a new shell which doesn't inherit the current shell's in-memory history. At most, you can get it to load in your shell's history file (e.g. ~/.bash_history), or extract the last two lines of that file with tail. The history file probably won't have whatever commands you've run in the current shell session, only whatever was most recently saved to it. – cas Feb 17 '22 at 09:46
  • @fuzzydrawings Not quite, I haven't been able to get something working yet, but it was a helpful read, I'm trying something now along the lines of what cas suggested. Extracting the last three lines should actually work for my purposes, and then it'd just be a matter of executing the -3rd and -2nd prior commands, since the last run command would be the script itself. – supersmarty1234 Feb 17 '22 at 17:15

0 Answers0