Remote for-loop over SSH

I have the following in a script

for server in ${servers[@]}; do
    echo ${server}
    ssh <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="473234223507">[email protected]</a>${server} "for i in /tmp/foo* ; do echo ${i}; done"
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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

ssh <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47323422350734282a226934223531692235">[email protected]</a> "for i in /tmp/foo* ; do echo; done"

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

ssh <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c2c4d2c5f7">[email protected]</a>${server} 'for i in /tmp/foo* ; do echo $i; done'

Method 2

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.

Method 3

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};
do
        for j in {5501,5502,5503,5504,7701,7702,7703,7704,5551,5552,5553,7771,7772,7773};
        do
                (echo > /dev/tcp/${i}/${j}) > /dev/null 2>&1 && echo "${i}:${j} :: it's getting connected" || echo "${i}:${j} :: it's not connecting"
        done
done


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x