4

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

0

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Re "You want eval": Do you mean "You don't want eval"? Or "You want eval, but"? Or something else?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.