Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store last command in a variable in Bash

Tags:

bash

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?

like image 237
Hank Phung Avatar asked Nov 21 '16 08:11

Hank Phung


People also ask

How do you put a command in a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...] arg1 arg2 ...'

How do I echo the last command?

As I mentioned earlier, we can execute the last command by simply pressing the UP arrow and hit ENTER key. This is the most commonly used way by many users to execute the previous command. This method will work on all SHELL, regardless of the Linux distribution you use.

How do I run the last command in bash?

Just press the Ctrl and P keys together to fill the prompt with the last executed command and you are ready to go. This method works in bash perfectly even after closing the terminal, but it might not work in zsh after closing the session.


1 Answers

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

some_var=$(fc -nl -1)
like image 84
codegrep_admin Avatar answered Oct 13 '22 19:10

codegrep_admin