If you want to use the output of the history
command from an active shell session in a script, you can use an alias to run the command first. Then, in the same alias, you can call the remainder of the script. With such a configuration, you can achieve essentially the same result as having the history
command in the actual script.
For instance, you can create an alias like this, assuming the script's name is script.sh:
alias hy_tmp='history | tail -100 > /tmp/history.log ; bash /patch/to/script.sh'
And change the script to this:
#!/bin/bash
cd /tmp
uuencode history.log history.txt | mail -s "History log of server" hello@hel.com
I found this question while writing a process to combine, sort and synchronize ~/bash_history
files on two computers so it'll be easy to search commands I've used in the past.
It's much less of a hassle to update my cumulative history file without having to log into a new shell to have ~/bash_history
updated. For monitoring a server this will obviously not work, as mentioned in the other answers.
My usage in particular is:
alias hbye='history | cut -c 8- > /home/chris/.bash_history_c; bash /hby.sh
The script hby.sh
then pulls all unique entries from all ~/.bash_history*
files.
histtest.sh: 5: set: Illegal option -o history
– Ken Sharp Jan 07 '16 at 02:56sh
is dash juding by the exact wording of the error message). To access bash's history, you need to use bash (script starting with#!/bin/bash
or#!/usr/bin/env bash
). – Gilles 'SO- stop being evil' Jan 07 '16 at 12:36Illegal option
(it would sayset: history: invalid option name
). – Gilles 'SO- stop being evil' Jan 07 '16 at 15:45set -o history
to the history which is then going to be stuffed up with entries likeif [...
vars=$(...
etc. – nath Dec 18 '17 at 02:42set -x
is a lot more useful. – Gilles 'SO- stop being evil' Dec 18 '17 at 08:19