Additional trick for http://ss64.com/bash/for.html

Bash shell questions
Post Reply
User avatar
MigrationUser
Posts: 336
Joined: 2021-Jul-12, 1:37 pm
Contact:

Additional trick for http://ss64.com/bash/for.html

Post by MigrationUser »

31 Mar 2006 17:04
Setsunaaa


On IRC I got told following trick for "for":

Code: Select all

IFS=":"
What does it change? Normally the "for" loop uses " " as seperator but this can be changed by setting the IFS environment variable.
I got it told when playing 'round with my firewall and had to work with a massive number of portforwardings.

Example for a nice IFS usage:

Code: Select all

#!/bin/bash

PORTFORWARD_TCP_SIMPLE="192.168.0.8:1279:267:4888:5550 192.168.0.55:4889:5551:32767 \
  192.168.0.78:5998:5500:2846:12223"
for X in ${PORTFORWARD_TCP_SIMPLE} ; do
  XIP="leer"
  IFS=":"
  for Y in ${X} ; do
    if [ "$XIP" = "leer" ] ; then
      XIP=$Y
    else
      iptables -t filter -A INPUT -p tcp -s ! 192.168.0.0/16 --dport $Y -j ACCEPT
      iptables -t filter -A FORWARD -p tcp -s ! 192.168.0.0/16 --dport $Y -j ACCEPT
      iptables -t nat -A PREROUTING -s ! 192.168.0.0/16 -p tcp --dport $Y -j DNAT --to $XIP
    fi
  done
  IFS=" "
done
We should NOT forget to IFS=" ", or it might mess up quite some other scripting.

----------------------------

#2 27 Jul 2006 20:26
Simon Sheppard


Good tip, but note that IFS (Internal Field Separators) is normally set to:

space tab newline

If you unset IFS only spaces and tabs will work as Field Separators

This will restore the default:

Code: Select all

% IFS=' \t\n'
----------------------------

#3 28 Jul 2006 21:11
Setsunaaa
Simon Sheppard wrote:

restore the default: IFS=' \t\n'
Ah, thank you, I'll have to correct some scripts now smile.

Well, it took long for the reply, did you accidently stumble over my post or did someone point you there? Just curiosity...

----------------------------

#4 29 Jul 2006 19:11
Simon Sheppard
Setsunaaa wrote:
Simon Sheppard wrote:

restore the default: IFS=' \t\n'
Ah, thank you, I'll have to correct some scripts now smile.

Well, it took long for the reply, did you accidently stumble over my post or did someone point you there? Just curiosity...
Just been real busy of late :0)

----------------------------

#5 28 Nov 2006 08:52
JayJayAitch


Even better would be to cache the old IFS:

Code: Select all

OFS=$IFS

# do your thing

IFS=$OFS
Last edited by JayJayAitch (28 Nov 2006 09:24)

original thread: https://ss64.org/oldforum/viewtopic.php?id=62
Post Reply