Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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?

like image 360
Ray Andrews Avatar asked Oct 23 '22 19:10

Ray Andrews


2 Answers

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
    
like image 55
sehe Avatar answered Oct 27 '22 10:10

sehe


$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.

like image 26
Ignacio Vazquez-Abrams Avatar answered Oct 27 '22 09:10

Ignacio Vazquez-Abrams