1984 – the techblog

(Hopefully) useful various sysadmin and other stuff.

Bash: Preparing and executing commands in a variable/string

When writ­ing some shell scripts, one does often have command’s argu­ments and options pre­pared in a vari­able. Aside from the usual quo­ta­tion rules, this usu­ally works fine:

> cmd="ls -a"
> $cmd
. .. dir1 dir2 dir3 file1 file2

Don’t do this any­more. It only works eas­ily for sim­ple com­mands. As soon as you’ve got more com­plex state­ments, you’ll get var­i­ous error mes­sages about argu­ments, hard to debug, almost impos­si­ble to solve. To fully under­stand this, you would’ve to read Sec­tion 3.5 of the Bash Ref­er­ence Man­ual. But, spare your­self the has­sle and just do

> eval "$cmd"

in the future. This will save you a lot of trou­ble (but it doesn’t free you from mak­ing sense in $cmd …).

Leave a Reply