ooXei1sh
ooXei1sh

Reputation: 3539

Bash script how to execute a command from a variable

I am trying to alter the Bash function below to execute each command argument. But when I run this script, the first echo works as intended, but the second echo that attempts to append to the scratch.txt file does not actually execute. It just gets echo'd into the prompt.

#!/bin/sh
clear

function each(){
  while read line; do
    for cmd in "$@"; do
      cmd=${cmd//%/$line}
      printf "%s\n" "$cmd"
      $cmd
    done
  done
}

# pipe in the text file and run both commands
# on each line of the file
cat scratch.txt | each 'echo %' 'echo -e "%" >> "scratch.txt"'

exit 0

How do I get the $cmd variable to execute as a command?

I found the original code from answer 2 here: Running multiple commands with xargs

Upvotes: 4

Views: 6875

Answers (1)

ghoti
ghoti

Reputation: 46826

You want eval. It's evil. Or at least, dangerous. Read all about it at BashFAQ #48.

Upvotes: 6

Related Questions