Reputation: 2612
I am pretty inexperienced with bash. I am trying to save the last run command as a variable, this is what I have:
#!/bin/bash
prev=$(fc -ln -1)
echo $prev
This doesn't print anything. Once I save the last command, I plan on coding this line:
valgrind --leak-check=full $prev
So what am I doing wrong?
Upvotes: 0
Views: 496
Reputation: 7659
I'd use aliases rather than a script, something like:
alias val='valgrind --leak-check=full'
alias vallast='val $(history 2 | head -1 | cut -d" " -f3-)'
As explained in the link, you can add these lines to your .bashrc
.
BTW, the latter can also be executed as:
val !!
val !-1 #same
Or if you want to valgrind
the program you ran 2 commands ago:
val !-2
These history commands are explained here.
Upvotes: 1
Reputation: 1184
fc
references the history of the current shell. When run inside a shell script it refers to history of that new shell. If you use an alias or shell function, then fc
will operate within the current shell. You can also source a script file for the same effect.
$ cat go
#!/bin/bash
set -o history
echo a b c
fc -nl -1
$ ./go
a b c
echo a b c
$ alias zz='fc -nl -1 | tr a-z A-Z'
$ zz
ALIAS ZZ='FC -NL -1 | TR A-Z A-Z'
Upvotes: 1