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?
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 ...'
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.
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.
The fc
command can be used to retrieve the previous command.
some_var=$(fc -nl -1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With