Jakub
Jakub

Reputation: 13

Variable still doesn't work on remote server

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

Upvotes: 1

Views: 49

Answers (2)

chepner
chepner

Reputation: 532093

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'

Upvotes: 1

choroba
choroba

Reputation: 242113

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.

Upvotes: 3

Related Questions