3

I try to use history command in a bash script but it didn't work.

The code of the bash file:

#!/bin/bash

# Copy history to file history 

#cd /media/saleel_almajd/Study/linux/my_scripts/
echo "start Copy history to /media/saleel_almajd/Study/linux/my_scripts/history.txt"
export HISTTIMEFORMAT='%F %T ' #to make history and date apear
history >> /media/saleel_almajd/Study/linux/my_scripts/history.txt
#cd 
echo "... copy done ..."
#history -c
echo "..... history cleared ..... "

echo "___ Done Successfully ___"
2
  • This makes no sense to me: you're running a script, so you know exactly what commands were executed. Why do you need history? Nov 7, 2014 at 1:46
  • To copy it in an external file to restudy this commands i am new at linux Nov 7, 2014 at 3:34

3 Answers 3

4

history is disabled by default in non-interactive shells by bash. You have to enable it.

The script should look like this:

#!/bin/bash

HISTFILE=~/.bash_history  # Set the history file.
HISTTIMEFORMAT='%F %T '   # Set the hitory time format.
set -o history            # Enable the history.

file="/media/saleel_almajd/Study/linux/my_scripts/history.txt"

history >> $file          # Save the history.
history -cw               # Clears the history of the current session.

Reference:

7
  • now it is work the history really copy to the dest file Nov 6, 2014 at 22:47
  • but it doesnt clear the history Nov 6, 2014 at 22:48
  • @SaleelAlmajd history -c clears history in memory. You have to then use history -w to write the empty history to the history file.
    – muru
    Nov 6, 2014 at 22:51
  • thanx to u but it still didnt work Nov 6, 2014 at 22:58
  • @muru: I edited your answer to include the complete code and correct the shebang. Feel free of revert it.
    – 0x2b3bfa0
    May 21, 2015 at 11:11
1

When you run script, it runs in another shell in background not the current one. So, the effect to this script will be in that another shell. If you want to make effect to the current shell, you must precede dot before script. Change directory to your current script then, issue: . scriptname instead of ./scriptname

1
  • where can i change this statment Nov 7, 2014 at 22:59
0
history command is disabled by default on bash script that's why even 
history command won't work in .sh file. for its redirection, kindly
redirect bash_history file inside the .sh file.

or history mechanism can be enabled also by mentioning history file and
change run-time parameters as mentioned below

#!/bin/bash
HISTFILE=~/.bash_history
set -o history 

note: mentioned above two lines on the top of the script file. now history command will work in history.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .