This one is a bit tricky. The information that Hauke has provided is correct, it's just a matter of parsing it out for your use case.
The easiest way is to use the
$() syntax while escaping the
$ such that the variable definition does not execute the command enclosed by the
$() at the time of definition. The caveat is that the end result must then be re-evaluated (via
eval) by the shell at the time of actual execution for the nested command to execute.
It's much easier to look at an example, so take this one, which should put you on the right track:
date +%s.%N # Print a timestamp (in format seconds.nanoseconds)
test="echo \$(date +%s.%N)" # Save a command to do the same
sleep 1 # Sleep for a second
eval "$test" # Evaluate the command saved in variable 'test'
echo # Print a new line before the next iteration
Here's sample output from the example above (trimmed to one iteration):
You'll notice that the second timestamp for each loop is about a second after the first. Conversely, if you perform the same test without escaping the
$ in the
test definition and removing the
eval, the two timestamps will nearly match.
Don't get in the habit of using
eval in most situations, but this is one of those where I don't know of a good way to avoid it. Hopefully this helps. Good luck!