Bash – “history” stops working when run inside bash script

bashcommand historyshell-script

I am writing a simple script to grep my bash history to find a particular string. On the command line, I can do the following, which works fine:

history | grep git

However, when I create a bash script with the same command as above, suddenly history returns nothing:

#!/bin/bash
history | grep git

When I remove the first line #!/bin/bash, my script works again. What is happening here? How can I use history inside a bash script?

Best Answer

The following is for bash 4.0 or higher only, but it does the trick. :)

#!/bin/bash -i
history | grep sometext

Works! Try it out. (-i = interactive, a flag not available to bash 3.x and earlier)

Related Question