Reputation: 4436
I guess this is easy but I couldn't figure it out. Basically I have a command history file and I'd like to grep a line and execute it. How do I do it?
For example: in the file command.txt file, there is:
wc -l *txt| awk '{OFS="\t";print $2,$1}' > test.log
Suppose the above line is the last line, what I want to do is something like this
tail -1 command.txt | "execute"
I tried to use
tail -1 command.txt | echo
but no luck.
Can someone tell me how to make it work?
Thanks!
Upvotes: 0
Views: 591
Reputation: 25
if you are expecting to execute the line several times in this bash session, consider adding it to an alias:
alias aa="$(tail -1 command.txt)"
then you could use aa<CR>
to execute the content from the line.
Upvotes: 0
Reputation: 3646
You can use eval
.
eval "$(tail -n 1 ~/.bash_history)"
or if you want it to execute some other line:
while read -r; do
if some condition; then
eval "$REPLY"
fi
done < ~/.bash_history
Upvotes: 1
Reputation: 530940
You can load an arbitrary file into your shell's history list with
history -r command.txt
at which point you can use all the normal history expansion commands to find the command you wish to execute. For example, after executing the above command, the last line in the file would be available to run with
!!
Upvotes: 4
Reputation: 11593
Just use command substitution
bash -c "$(tail -1 command.txt)"
Upvotes: 3
Reputation: 10122
Something like that?
echo "ls -l" | xargs sh -c
This answer addresses just the execution part. It assumes you have a method to extract the line you want from the file, perhaps a loop on each line. Each line of the file would be the argument for echo
.
Upvotes: 1