2

I saw the following example for reading a file in a bash script:

while read IP; do
  ${IPTABLES} -I INPUT -s "${IP}" -j DROP
done < <(cat "${BLACKLIST}")

but I'd have thought to do the following instead:

while read IP; do
  ${IPTABLES} -I INPUT -s "${IP}" -j DROP
done <${BLACKLIST}

Why would one use < <(cat instead of simply <? What is the right-est way to do this?

Second comment on this question gives good reason why using cat is bad but RoseHosting.com seems pretty reputable and they suggest the code above that uses cat. I'm thinking the < <(cat file) looks like a weird way to cover up a bad practice. (here's another place it was pointed out cat piping to a loop is bad)

Community
  • 1
  • 1
Still.Tony
  • 1,437
  • 12
  • 35
  • 1
    As far as I'm aware the `cat` version is never preferable. It is purely more costly and less portable. – Etan Reisner Feb 18 '15 at 03:02
  • Here's the code source for the `< <(cat file)`: https://www.rosehosting.com/blog/blocking-abusive-ip-addresses-using-iptables-firewall-in-debianubuntu/ – Still.Tony Feb 18 '15 at 03:04
  • 1
    *shrug* people cargo-cult and/or write poor shell scripts all the time. – Etan Reisner Feb 18 '15 at 03:07
  • @EtanReisner which is exactly what I'm trying *not* to do here. I went through the script line by line and understand all but that usage. – Still.Tony Feb 18 '15 at 03:09
  • 5
    `cat` is useful when you want input from more than one file. So, if the code were `cat "$BLACKLIST1" "$BLACKLIST2"`, then `cat` would be useful. In RoseHosting's case, it seems completely useless. – John1024 Feb 18 '15 at 03:11
  • `cat` might have use when reading from some non-file locations that might behave badly with whatever the shell does internally but which `cat` handles more gracefully (open errors ending up with empty input versus some other failure or something) but I don't know if that's possible. – Etan Reisner Feb 18 '15 at 03:12
  • Sounds reasonable but even in their script the file existence is checked right before the loop. – Still.Tony Feb 18 '15 at 03:14

1 Answers1

1

It's a useless use of cat. The only legitimate reason one might use it with a single file is for legibility (e.g. cat file | while ...), but in this case it only becomes more convoluted.

Ben Grimm
  • 4,316
  • 2
  • 15
  • 24