1

Is it possible to use history expansion within a trap [commands] ERR?
I've tried manually enabling history expansion within the environment and within the trap commands argument (trap 'set -H; echo !-2 failed' ERR) but could not get it to work as the shell always ended up just interpreting "!-2" literally.

Every designator I've tried from Bash's manual ended up being interpreted literally once the trap got activated but they work just fine when called somewhere else in the same environment.

Davi
  • 11
  • 2
  • 3
  • 1
    Are you running this in a script? – KamilCuk Jul 23 '20 at 13:03
  • @KamilCuk Yes, I am. – Davi Jul 23 '20 at 15:46
  • There is "history" in noninteractive scripts (well, unless you enable it). How doesn't `BASH_COMMAND` or https://unix.stackexchange.com/questions/39623/trap-err-and-echoing-the-error-line doesn't do what you want? Isn't this XY question. You are _not_ interested in expanding `!-2` in `trap` context... What you are interested, is how to get failed command in ERR trap.. – KamilCuk Jul 23 '20 at 15:54

1 Answers1

0

!-2? Use:

history | tail -n2 | head -n1

or just:

history -p '!-2'
KamilCuk
  • 120,984
  • 8
  • 59
  • 111