1

Suppose we have env.sh file that contains:

echo $(history | tail -n2 | head -n1) | sed 's/[0-9]* //' #looking for the last typed command

when executing this script with bash env.sh, the output will be empty:

enter image description here

but when we execute the script with ./env.sh, we get the last typed command:

enter image description here

I just want to know the diffrence between them

Notice that if we add #!/bin/bash at the beginning of the script, the ./env.sh will no longer output anything.

1 Answers1

2

History is disabled by BASH in non-interactive shells by-default. If you want to enable it however, you can do so like this:

#!/bin/bash

echo $HISTFILE # will be empty in non-iteractive shell

HISTFILE=~/.bash_history # set it again
set -o history
# the command will work now
history

The reason this is done is to avoid cluttering the history by any commands being run by any shell scripts.

Adding hashbang (meaning the file is to be interpreted as a script by the program specified in your hashbang) to your script when being run via ./env.sh invokes your script using the binary /bin/bash i.e. run via bash, thus again printing no history.

Jarvis
  • 8,494
  • 3
  • 27
  • 58