chuacw
chuacw

Reputation: 1863

How do I execute a command in a variable in Bash?

If I have a script such as the below where I define a command to run in CMD_VAR, a variable, how do I get it executed in the same Bash script?

I do it this way because I want to log CMD_VAR to a file as well.

#!/bin/sh
CMD_VAR="echo hello world >> somelogfile"

Upvotes: 0

Views: 108

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

In general you should not store redirections in a variable. And you should store commands in an array.

cmd=(echo "hello world")
log="somelogfile"
"${cmd[@]}" >> "$log"

Upvotes: 5

Related Questions