4

I have the following Bash script

case $- in (*H*) echo enabled ;; (*) echo disabled ;; esac
set -H
case $- in (*H*) echo enabled ;; (*) echo disabled ;; esac
pwd
last_command="!!"
echo $last_command

which prints

disabled
enabled
/home/user
!!

The first line of code checks to see if history expansion is enabled. The second enables history expansion. The third is the same as the first. Then its runs pwd and finally assigns what should be last command to last_command and prints this variable.

The history is not expanding. What is going on?

1 Answers1

3

For a non-interactive shell, you must specifically also enable command history:

set -o history
set -o histexpand

Then your example will work:

disabled
enabled
/home/schaller/tmp/502442
last_command="pwd"
pwd
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • Thanks, how do I make is so that I can access the history from the shell that is running the script and use history expansion is a similar fashion? – History_expansion Feb 23 '19 at 02:53
  • @History_expansion According to this history expansion is disabled for scripts by default (which is also mentioned under appropriate section in bash manual) and you should be able to enable that via set -H – Sergiy Kolodyazhnyy Feb 23 '19 at 04:26
  • @SergiyKolodyazhnyy I did that and showed it my question, it doesn't work. – History_expansion Feb 23 '19 at 11:48
  • @History_expansion let's make a new question out of it. Describe exactly what you want to happen. I'm curious why you need the behavior, and if sourcing the script could be an option. Thanks! – Jeff Schaller Feb 23 '19 at 13:49
  • @JeffSchaller https://unix.stackexchange.com/questions/502526/using-interactives-shell-history-expansion-inside-a-script Thanks. I need this behavior because there's a blackbox in the company that reads a script (the script that I'm trying to write). I don't really need history expansion, I can do it in other ways, I'm very curious in how to get history expansion to work to this effect. – History_expansion Feb 23 '19 at 14:41