-1

I am trying to add lines from a file to my history, but it just adds the program code! What am I doing wrong?

#!/bin/bash 
HISTFILE=~/.bash_history
set -o history
cat file.txt | while read line
do
  echo "$line"
  history -s $line
done

It adds cat file.txt | while read line; do echo "$line"; history -s $line; done instead of each line inside file.txt (foo,bar,etc).

  • 1
    Why don't you just append the lines to ~/.bash_history directly? – Byte Commander Apr 19 '17 at 22:40
  • 1
    I don't understand why you would want to do it like that, but probably what you're bumping up against is that (in bash, and many other shells) the RHS of the pipe is executed in a separate subshell - see for example Why is my variable local one 'while read' loop, but not in another seemingly similar loop? – steeldriver Apr 19 '17 at 22:52
  • @ByteCommander Actually, appending to .bash_history would only affect a new / reset bash, it doesn't change the current history - i.e. can't access the new entries in the current bash session. (FYI, the call to history itself is not saved in the history) – Xen2050 Apr 19 '17 at 23:34
  • @steeldriver can you think of a better way – lol Apr 20 '17 at 0:47
  • @lol But you can use history -r from your current Bash session to re-read the history file and append all new lines from there to your in-memory history buffer. – Byte Commander Apr 20 '17 at 7:59
0

To me at least, it seems like you could just run cat file.txt >> $HISTFILE. However, as Xen2050 said, it will not update until you restart bash.

0

First, append your file directly to the history file:

cat file.txt >> ~/.bash_history

Then, to get the additional lines immediately in your current Bash session, tell it to re-read the history file and append its new lines to the current history list in memory:

history -r

For more info, type help history, man history or man bash.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.