4

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

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Only one thing, if I am correct , then history is user-scoped, in the sense of if you will run some commands like in order with user switch, then in origin user history you will probably find only switch to user, not the commands which ran under new user (ask you can see there is ~ in the path for bash_history file)
I understand, although I am not sure the OP wants to consider the case of switching users.
@FabioA.Correa yep, I don’t care, I’m coding for myself :)
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.