Bash: Preparing and executing commands in a variable/string
When writing some shell scripts, one does often have command’s arguments and options prepared in a variable. Aside from the usual quotation rules, this usually works fine:
> cmd="ls -a" > $cmd . .. dir1 dir2 dir3Â file1 file2
Don’t do this anymore. It only works easily for simple commands. As soon as you’ve got more complex statements, you’ll get various error messages about arguments, hard to debug, almost impossible to solve. To fully understand this, you would’ve to read Section 3.5 of the Bash Reference Manual. But, spare yourself the hassle and just do
> eval "$cmd"
in the future. This will save you a lot of trouble (but it doesn’t free you from making sense in