Operating System - HP-UX
1753797 Members
7119 Online
108799 Solutions
New Discussion

Re: for loop question and change of IFS

 
SOLVED
Go to solution
support_billa
Valued Contributor

for loop question and change of IFS

hello,

i am wondering , why a for-loop doesn't work

i store hostname's in variable  and then i use "for"

 

COPY_HOSTS="host1 host2"


for copy_host in ${COPY_HOSTS}
do
  echo "copy_host: ${copy_host}"
done

###########################

output ( ok )
copy_host: host1
copy_host: host2

 

but then i am wondering, when this statement doesn't work in a big shell script and produces following output:

 

copy_host: host1 host2

 

then i try to fix it and found statements above like " while IFS=':'  ".

this has a impact for a "for loop" in this case ?

 

so i save  before the "for loop" the IFS

SAVE_FS="${IFS}"

IFS=" "

right ?

after "for loop"

IFS="${SAVE_FS}"

 

regards

 

 

2 REPLIES 2
Dennis Handly
Acclaimed Contributor

Re: for loop question and change of IFS

>found statements above like " while IFS=':'  ". This has a impact for a "for loop" in this case?

 

Right.  If IFS isn't set to split up the variable COPY_HOSTS, there is only one string there.

 

>so I save  before the "for loop": SAVE_FS="${IFS}"

>IFS=" "

>after "for loop": IFS="${SAVE_FS}"

 

Yes.  Or set it to the default, " \t\n", where \t is really a tab and \n is really ctrl-V ctrl-J.

 

James R. Ferguson
Acclaimed Contributor
Solution

Re: for loop question and change of IFS

HI:

 

In my opinion, the safest way to change the shell's IFS is to save the old value and restore that after your operations are complete:

 

OLDIFS=${IFS}
...
IFS=${OLDIFS}

If you try to set to the IFS to whitespace (a blank, a tab, and/or a newline) and ever use 'expand' to change your script's tab to strings of blanks you will be unpleasantly surprised.

 

Regards!

 

...JRF...