You are not logged in.

#1 31 Mar 2006 17:04

Setsunaaa
Member
Registered: 31 Mar 2006
Posts: 2

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

On IRC I got told following trick for "for":
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:

#!/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.

Offline

#2 27 Jul 2006 20:26

Simon Sheppard
Admin
Registered: 27 Aug 2005
Posts: 1,130
Website

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

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:

% IFS=' \t\n'

Offline

#3 28 Jul 2006 21:11

Setsunaaa
Member
Registered: 31 Mar 2006
Posts: 2

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

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

Offline

#4 29 Jul 2006 19:11

Simon Sheppard
Admin
Registered: 27 Aug 2005
Posts: 1,130
Website

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

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)

Offline

#5 28 Nov 2006 08:52

JayJayAitch
Member
From: The Netherlands
Registered: 28 Nov 2006
Posts: 1

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

Even better would be to cache the old IFS:

OFS=$IFS

# do your thing

IFS=$OFS

Last edited by JayJayAitch (28 Nov 2006 09:24)

Offline

Board footer

Powered by