2

I have a frequent situation where I want to run a given command over all files that match a certain pattern. As such I have the following:

iterate.sh

#!/bin/bash
for file in $1; do
    $2
done

So I can use it as such iterate.sh "*.png" "echo $file"

The problem is when the command is being ran it doesn't seem to have access to the $file variable as that sample command will just output a blank line for every file.

How can I reference the iterator $file from the arguments of the program?

1 Answer 1

3
#!/bin/bash
for file in $1; do
    eval $2
done

iterate.sh "*.png" 'echo $file'

Need single quotes around the argument with $file so it doesn't expand on the command line. Need to eval in the loop to actually do the command in the argument instead of just expanding the argument.

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

1 Comment

Ah perfect. I'd tried eval, but not with the single quotes. I'll accept in 7 min.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.