Search code examples
linuxbashunixscriptingifs

When should we change the IFS variable back to its original value in scripts?


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?


Solution

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