This question already has an answer here:

I have a list of commands in a file called cmds, one command per line.

I want to grab the last command, set it in a variable last_command and run it later. with $last_command or "$last_command", or whatever is more appropriate.

I start by getting the last command:

$ last_command="$(cat cmds | tail -1)"
$ echo $last_command
cat file1 file2 file\ 3

The last line of cmds was cat cat file1 file2 file\ 3.

The problem is, when I run "$last_command", it will not know that the space between file and 3 is part of the file name and give me an error.

marked as duplicate by αғsнιη, Community Apr 15 at 11:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


Assuming your commands in file are correct and have all required spaces escaped evil eval will help you. Instead of $last_command execute this one:

eval $last_command

PS. eval normally is not considered as best practices as it easily might lead to security issues.

Not the answer you're looking for? Browse other questions tagged or ask your own question.