“history position out of range” when calling history from bash script

bashcommand history

I want to make a simple script to delete a line from bash_history, based on user input of the line number.

echo -n "Delete History Line Number: "
read num
history -d $num

The error is "history position out of range" (which it shouldn't be, I'm using a number within range).

Why doesn't this work?

Best Answer

There are two reasons why your script will not work as intended:

  1. The bash environment for a running script is "non-interactive" and does not have the history features enabled.
  2. The bash environment for a running script is independent from the environment you are interactively working in.

Depending on your use case the easiest solution might be to source the script, instead of executing. See the SU post explaining the difference of sourcing and executing for more information.

Related Question