I have the following in a script

for server in ${servers[@]}; do
 echo ${server}
 ssh user@${server} "for i in /tmp/foo* ; do echo ${i}; done"

But it doesn't work. Weird thing, I see $I amount of return lines. So if I have ten files, I see ten blank lines.


Your local shell interpretes the ${i} within double quotes ("), so the command works out to

ssh user@some.serv.er "for i in /tmp/foo* ; do echo; done"

Simply use single quotes (') instead and your problem will disappear:

ssh user@${server} 'for i in /tmp/foo* ; do echo $i; done'

Just ran into this problem a bit back, and the solution given, while it does work is not too effective if you're also pulling in variables from the local shell, prior to the ssh you create an array to iterate over. A bit messier somewhat would be to just escape the $ initially so it'd be

"for i in /tmp/foo* ; do echo \${i}; done"

Which would escape it within the local construct, not the called ssh shell.


I have updated above answer to get ports from a list too.

for i in {10.21.xxx.yyy,10.21.xxx.yyy,10.23.xxx.yyy};
        for j in {5501,5502,5503,5504,7701,7702,7703,7704,5551,5552,5553,7771,7772,7773};
                (echo > /dev/tcp/${i}/${j}) > /dev/null 2>&1 && echo "${i}:${j} :: it's getting connected" || echo "${i}:${j} :: it's not connecting"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.