문제

Let's say I execute this script via a cronjob:

IFS=$'\n'

for i in `cat "$1"`; do
    echo "$i" >> xtempfile.tmp;
done

It works fine without causing any issues. But when I run this in a terminal, I have to set IFS variable back to its original value

IFS=$OLDIFS

Generally in which cases should we have to set IFS back to its original value?

도움이 되었습니까?

해결책

Instead of:

IFS=$'\n'

for i in `cat "$1"`; do
    echo "$i" >> xtempfile.tmp;
done

You can do something like:

while IFS=$'\n' read -r line; do
echo "$line"
done < "$1" >> xtempfile.tmp

This would set the IFS variable for the duration of while loop.

*Addition based on samveen's comments. Anytime a change is made to IFS in a subshell, the changes are reverted automatically. However, that is not true when you made modifications in interactive shell. The above suggestion is the required handling done to ensure we don't accidentally modify the IFS for the entire shell. *

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top