0

I have this part of script, which I cannot get to work. Been searching everywhere, but I must be missing something here.

export RULE=`cat iptables_sorted.txt` 
ssh hostname << EOF
for line in $RULE; do
echo \$line >> test.txt (I have tried with and without slashes, etc...)
done
exit
EOF

After running this part of script, I get

stdin: is not a tty
-bash: line 2: syntax error near unexpected token `103.28.148.0/24'
-bash: line 2: `103.28.148.0/24'

...which is totally weird, because the iptables_sorted.txt is just full of ip ranges (when I run it locally, it works).

choroba
  • 231,213
  • 25
  • 204
  • 289
Jakub
  • 3
  • 2
  • How about this thread: http://stackoverflow.com/questions/4412238/whats-the-cleanest-way-to-ssh-and-run-multiple-commands-in-bash , I also don't think you're supposed to use CIDR when trying to connect using ssh, use a specific address. – Yaron Oct 21 '15 at 08:53
  • @Yaron that is not the problem, that cidr comes from the local text file and OP is trying to put it in a file on the remote server. – arco444 Oct 21 '15 at 09:07
  • The part with connecting to remote server is ok, the .txt file is generated there, but its empty. I think problem is somewhere in the variable, but I am not really sure what exactly is wrong. – Jakub Oct 21 '15 at 09:11
  • Is this just an example script? You seem to simply be copying a file to a remote host: `scp iptables_sorted.txt hostname:test.txt`. – chepner Oct 21 '15 at 12:09
  • This part "echo \$line >> test.txt" was just for testing purposes. I didnt want to do any system changes, when there was an error somewhere (just to be safe). The real purpose of it was to apply all the ranges from txt file to all servers at once. – Jakub Oct 21 '15 at 12:19

2 Answers2

3

Newlines in $RULE cause the problem. Replace them by spaces:

RULE=$(< iptables_sorted.txt)
RULE=${RULE//$'\n'/ }
ssh hostname << EOF
for line in $RULE ; do
    echo \$line >> test.txt
done    
EOF

Note that this wouldn't work with lines containing whitespace.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • Man! You are lifesaver. I though that the problem must have been in the variable, but for sure, I wouldnt figure it out. Thank You so much. – Jakub Oct 21 '15 at 09:15
0

Don't use for to iterate over a file; use while. This also demonstrates piping the output of the loop, not just every individual echo, to the remote host. cat is used to read the incoming data and redirect it to the final output file.

while IFS= read -r line; do
    echo "$line"
done | ssh hostname 'cat > test.txt'
chepner
  • 497,756
  • 71
  • 530
  • 681