Is there a way to pass in a variable as an argument to a bash script and have it evaluated scoped by the bash script?Given:# cat /path/to/file/of/host/namesbobtomjoeetc...# doforFILE=$1shiftCMD=$*while read host; do    # recursively turns ssh \$host hostname from $@ into:    # ssh bob hostname    # ssh tom hostname    # ssh joe hostname    # etc...    eval $CMDdone < $FILEWhen:# dofor /path/to/file/of/host/names ssh \$host hostnameThen: I'd receive the output from running ssh host hostname for each hostname listed in /path/to/file/of/host/names. e.g.:bob.example.comtom.example.comjoe.example.cometc...
Evalute passed in variable in bash
bash;shell;shell script;scripting
You can use#!/bin/bashFILE=$1exec 3<$FILEwhile read -u 3 host; do    $2 $host $3doneThen if you have:$ cat /tmp/hostnamessome.host1.comanother.host2.netsome.host3.org    some.host4.comand run dofor.sh /tmp/hostnames ssh ls, it will run in sequence:ssh some.host1.com lsssh another.host2.net lsssh some.host3.org lsssh some.host4.com lsEDIT1:If you'd like to change ssh or ls into some longer commands (or parts of such), just use quotes:dofor.sh /tmp/hostnames ssh -p 23 ls -lh /EDIT2:With the following script, you'll be able to use $host variable in as many places in your command as you want:#!/bin/bashexec 3<$1while read -u 3 host; do    eval $2done(I made this one shorter - no useless introducing of $FILE variable.)The important part here is that you need to use single quotes around the command containing the $host variable: dofor.sh /tmp/hostnames 'echo trying $host :; ssh -p 23 myuser@$host ls -lh /'But beware that it is dangerous to use eval (see l0b0's wall) because if the file /tmp/hostnames contained a command on some line, it would be executed. Better not use this as root!