在bash脚本中获取最后执行的命令名称

时间:2019-04-24 19:54:49

标签: bash

在bash脚本中,我想获取在终端中执行的最后一个命令的名称,并将其存储在变量中以备后用。我知道!:0在bash脚本中不起作用,我正在寻找替代它的方法。 例如:

#user enters pwd
> pwd
/home/paul
#I call my script and it show the last command
> ./last_command
pwd 

这无济于事,它只显示空行。 getting last executed command from script

2 个答案:

答案 0 :(得分:3)

告诉 shell 以将命令连续追加到历史记录文件中:

export PROMPT_COMMAND="history -a"

将以下内容放入脚本中:

#!/bin/bash

echo "Your command was:"
tail -n 1 ~/.bash_history

答案 1 :(得分:0)

就我从.bashrc中工作的人的利益而言;

export HISTCONTROL=ignoredups:erasedups

然后分别在控制台或脚本中执行

history 2

cm=$(history 1)
相关问题