In Bash we can dynamically build and execute the commands. Below we can find two examples of building command stored in variable and then execute the commands to get result:
(1) eval - Build command and execute
cmd="echo Hello World!"
cmd_file="> out.txt"
eval ${cmd} ${cmd_file}
We build command: echo Hello World! > out.txt
from two variables and then execute it with eval
The result is creating a new file out.txt
and writing text: Hello World!
(2) $($cmd) - Execute command
cmd="ls -a"
res=$($cmd)
echo $res
Alternative solution is to use $($cmd)
to run a command which is stored in a variable. The result will be:
- create variable with
ls -a
command - execute the command
- print out the result
(3) Dynamically Build Command in script
#!/bin/bash
cmd="ls -a"
res=$($cmd)
echo $res
Saving the above as test.sh
. Next we can run the script by ./test.sh
.