Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 342
Vassilis Avatar asked Jun 19 '13 03:06

Vassilis


People also ask

What is the default value of IFS?

The default value of IFS is space, tab, newline. (A three-character string.) If IFS is unset, it acts as though it were set to this default value. (This is presumably for simplicity in shells that do not support the $'...' syntax for special characters.)

What is the use of IFS in shell script?

The shell has one environment variable, which is called the Internal Field Separator (IFS). This variable indicates how the words are separated on the command line. The IFS variable is, normally or by default, a white space (' '). The IFS variable is used as a word separator (token) for the for command.

What is the return value of a bash script?

Return Values Unlike functions in “real” programming languages, Bash functions don't allow you to return a value when called. When a bash function completes, its return value is the status of the last statement executed in the function, 0 for success and non-zero decimal number in the 1 - 255 range for failure.

What is IFS in while loop?

IFS is used to set field separator (default is while space). The -r option to read command disables backslash escaping (e.g., \n, \t). This is failsafe while read loop for reading text files.


1 Answers

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

like image 146
jaypal singh Avatar answered Sep 19 '22 05:09

jaypal singh