17

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"
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.

1

3 Answers 3

21

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

ssh [email protected] "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'
2
  • In your first code line, you want to show $i disappears because it is called local and not on the server?
    – Timo
    May 24, 2021 at 19:52
  • nope, doesn't work!
    – Vladmir
    Jun 9, 2022 at 22:48
5

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.

3
  • Do I get you right, you can pass a local variable to the shell env like a=5;server=ip1;ssh user@${server} "echo $a"? Does not work for me
    – Timo
    May 26, 2021 at 18:23
  • If you run the same command, but modify it to ssh user@${server} "echo \$(hostname) $a" you'd see the hostname of the server you're pointing to not your own. Also if the variables will only live for the life of that one command and you don't want to pollute your shell then a=5 server=ip1 ssh user@${server} "echo \$(hostname) $a would be a solution.
    – L.P.
    Jun 26, 2021 at 20:05
  • Works perfectly !
    – Vladmir
    Jun 9, 2022 at 22:48
0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .