I can’t seem to “access” the value of my loop variable when executing a command line argument in a Bash script. I’d like to be able to write something like
#!/bin/bash
for myvar in 1 2 3
do
$@
done
and run the script as ./myscript echo "${myvar}".
When I do this, the lines are echoed as empty. I probably don’t have a firm grasp one exactly what’s being evaluated where.
Is what I want even possible?
$myvaris evaluated before the child script is even run, so it can’t be evaluated within.That is, when you invoke your script as:
what is actually being called is:
presuming that
$myvaris empty in the enclosing environment.If you wanted to be evil (and this is evil, and will create bugs, and you should not do it), you could use eval:
…and then call as:
Something less awful would be to export a variable:
…but even then, the way you call the script will need to avoid preevaluation. For instance, this will work in conjunction with the above:
…but that basically has you back to eval. On the other hand:
…will do what you want, presuming that
otherscriptrefers to$myvarsomewhere within. (This need not be a shell script, or even a script; it can be an executable or other command, and it will still be able to findmyvarin the environment).What’s the real goal (ie. business purpose) you’re trying to achieve? There’s probably a way to accomplish it better aligned with best practices.