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?
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.)
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.
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.
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.
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. *
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With