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
  • 333,661

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
  • 333,661