kalenpw
kalenpw

Reputation: 695

Bash access for loops variable via command passed as argument

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?

Upvotes: 2

Views: 35

Answers (1)

jeremysprofile
jeremysprofile

Reputation: 11425

#!/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.

Upvotes: 3

Related Questions