• Uncategorized

About bash : Store-last-command-in-a-variable-in-Bash

Question Detail

I’m want to store the most recent command in a variable. I tried the !!:p history expansion, it does get me the last command but I can’t store it in a variable.

$ last=`!!:p`
last=`ls`
$ echo $last

$

Any help?

Question Answer

The fc command can be used to retrieve the previous command.

some_var=$(fc -nl -1)

Using !!:p only prints the last command, to execute the last command you would do !!.

$ mycmd="$(!!)"
$ sh "$mycmd"

That should do what you’re looking for…

The solution given above does not work inside a script file:

some_var=$(fc -nl -1)

What I did was use trap option and store the last command in environment variable before the script is called and access the env variable in script.

Add this function in ~/.bashrc

function process_command() {
  if [ "$BASH_COMMAND" != "$PROMPT_COMMAND" ];then
    export myCMD=$BASH_COMMAND
  fi
}
trap process_command DEBUG

Then use $myCMD variable in any script or anywhere in shell.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.