Ray Andrews
Ray Andrews

Reputation: 542

'history -s' in a script doesn't work

I'm relatively new to linux, and trying furiously to lean bash, and eventually zsh. Anyway, for the moment this has me stumped:

#!/bin/bash
history -s "a_string"

.... doesn't work. I've tried a dozen variations on the idea, but nothing cuts it. Any ideas?

Upvotes: 5

Views: 2203

Answers (2)

sehe
sehe

Reputation: 392929

The subshell is not interactive, and therefore doesn't save the history or the parent shell doesn't reload history.

Typical ways around this:

  1. use an alias instead of a script

       alias doit='history -s "a_string"'  
       unalias doit
    
  2. use a shell function instead of script

       function doit() { 
            echo "A function is a lot like a script"
            history -s "but operates in a subshell only when a bash command does (piping)" 
       }
       unset doit
    
  3. source the script, instead of executing it in a subshell

    source ./myscript.sh
    . ./myscript.sh   # equivalent shorthand for source
    

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

$HISTFILE and $HISTFILESIZE are not set when running a script like this. Once you set $HISTFILE you can read and write the history as you like.

Upvotes: 1

Related Questions