Reputation: 3177
I am trying to write a simple script that loads the iptables rules from a file to the iptables:
#!/bin/bash
set -euxo pipefail
test_file="test.conf"
while read line; do
echo $line
echo "-----"
iptables $line
done < $test_file
And the test.conf has some rules inside:
-A INPUT -p tcp -m tcp --dport 123 -m comment --comment "test 1" -j ACCEPT
-A INPUT -p tcp -m tcp --dport 112 -m comment --comment "test 2" -j ACCEPT
-A INPUT -p tcp -m tcp --dport 1231 -m comment --comment "test 3" -j ACCEPT
But when i run the script, it returns error as:
+ test_file=rules.conf
+ read line
+ echo -A INPUT -p tcp -m tcp --dport 123 -m comment --comment '"test' '1"'
-j ACCEPT
-A INPUT -p tcp -m tcp --dport 123 -m comment --comment "test 1" -j ACCEPT
+ echo -----
-----
+ iptables -A INPUT -p tcp -m tcp --dport 123 -m comment --comment '"test'
'1"' -j ACCEPT
Bad argument `1"'
Looks like whenever the file is run and if there is a space in the string, it will have a single quote to wrap around the space.
Is there a way to get rid of the behavior?
Upvotes: 0
Views: 35
Reputation: 10407
The last line is the main problem. The shell doesn't interpret quote marks during variable expansion. If you change that to
eval iptables $line
you should get (roughly) the right results.
Your read statement is also potentially problematic because you didn't set IFS to a newline first. This could cause multiple whitespace to be collapsed and other possibly undesirable behavior. So I would start with
IFS="
"
or similar.
Upvotes: 1