Pavlo Kovalov
Pavlo Kovalov

Reputation: 116

Getting last executed command name in bash script

In a bash script I want to get the name of the last command executed in terminal and store it in the variable for later use. I know that !:0 doesn't work in bash script, and I'm looking for some replacement of it. For example:

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

this didn't help, it just prints empty line. getting last executed command from script

Upvotes: 4

Views: 943

Answers (2)

user7712945
user7712945

Reputation:

as far as I benefit the working one in my .bashrc;

export HISTCONTROL=ignoredups:erasedups

then do this, on console or in script respectively

history 2

cm=$(history 1)

Upvotes: 1

Fabio A. Correa
Fabio A. Correa

Reputation: 2036

Tell the shell to continuously append commands to the history file:

export PROMPT_COMMAND="history -a"

Put the following into your script:

#!/bin/bash

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

Upvotes: 3

Related Questions