Aymanadou
Aymanadou

Reputation: 1220

Unset IFS value for shell script

In my use case I would like to change the value of IFS to a known separator (-). I tried the following:

OLDIFS=$IFS
IFS='-'
for x in $*
do
    echo $x
done
IFS=$OLDIFS

When using e.g. -a b -c d as input string I expect the output to be

a b
c d

However, what I get is

a
b
c
d

I'm on AIX.

Upvotes: 1

Views: 1726

Answers (2)

anubhava
anubhava

Reputation: 785846

Here is one way of getting this output using awk and avoid all the IFS manipulation:

s='-a b -c d'
echo "$s" | awk -F ' *- *' '{print $2 RS $3}'
a b
c d

Upvotes: 1

PeterMmm
PeterMmm

Reputation: 24630

I tried your code and I get

a b
c d

Try this

$ cat >a <<.
#!/bin/sh
OLDIFS=$IFS
IFS='-'
for x in $*
do
    echo $x
done
IFS=$OLDIFS
.
$ chmod +x a
$ ./a "-a b -c d"

a b
c d
$

Upvotes: 1

Related Questions