如何在 Bash 脚本中使用历史命令?

如何在 Bash 脚本中使用历史命令?

我尝试history在 Bash 脚本中使用命令,但没有作用。

bash文件的代码:

#!/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 ___"

答案1

history在非交互式 shell 中,默认情况下已禁用bash。您必须启用它。

该脚本应如下所示:

#!/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.

参考:

答案2

当您运行脚本时,它会在后台的另一个 shell 中运行,而不是当前 shell。因此,此脚本的效果将在另一个 shell 中。如果您想使当前 shell 生效,则必须在脚本前加上点。将目录更改为当前脚本,然后发出:.脚本名称代替./脚本名称

答案3

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 

注意:上面提到的脚本文件顶部的两行。现在 history 命令将在历史记录中起作用。

相关内容