1

I have a small script, which does not give comma separated output when IFS is used, but IFS is mandatory as i need it to read many other value. The output of the below script is odi_server1 odi_server2, but I need it separated by comma.

#Script Starts
#!/bin/sh

IFS=","
odi_cluster=odi_server1,odi_server2;
echo $odi_cluster;

#Script Ends

Current Output = odi_server1 odi_server2

Expected Output = odi_server1,odi_server2

Note:- IFS="," is mandatory, hence removing it is not an option.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
Priyanka
  • 11
  • 1
  • 2
  • 2
    The Input Field Separator is not used for output field separation. – ctrl-alt-delor Oct 06 '20 at 21:04
  • 3
    _Always_ double-quote your variables when you use them, i.e. `echo "$odi_cluster"` instead of `echo $odi_cluster`. – roaima Oct 06 '20 at 21:27
  • 4
    The shebang must be the first line in the file -- specifically, `#!` must be the first two characters in the script. – Paul_Pedant Oct 06 '20 at 22:03
  • In the suggested duplicate, please read the accepted answer, and particularly the second paragraph of its point (1). – roaima Oct 06 '20 at 22:39
  • 4
    @Paul_Pedant the missing double-quotes coupled with the `IFS` value is exactly the problem – roaima Oct 06 '20 at 22:58
  • @roaima Conceded absolutely. As I always quote, and always set IFS as a local export only, I never ventured into this particular morass. – Paul_Pedant Oct 07 '20 at 10:59
  • By the way, you probably could have found that out yourself had you searched for "IFS" in the bash man page and read through the first paragraph with a match. – Johannes Riecken Oct 08 '20 at 09:37

1 Answers1

2

Since you use $odi_cluster unquoted in the call to echo, the shell will split the variable's value on any character that also occur in $IFS (and then perform filename globbing on the generated words). Ordinarily, $IFS contains a space, a tab character, and a newline, but you've re-set it to be a comma.

If the variable's value is odi_server1,odi_server2 and $IFS contains a comma, this splitting results in the two words odi_server1 and odi_server2. These will be given to echo as two separate arguments and echo utility will output these with a separating space.

To avoid letting IFS have any effect on the output, prevent the shell from splitting the variable's value by quoting the expansion:

echo "$odi_cluster"

or

printf '%s\n' "$odi_cluster"

Related:

Note that you may set the IFS variable for only the read built-in utility by invoking read like

IFS=, read ...

This avoids setting IFS to a non-default value for the rest of the script.

Possibly also related:

Also note that the characters # and ! of the #!-line must be the very first characters of the file, and that you don't need to end each statement with a ; unless there are further statements on the same line.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936