In a bash shell, I want to convert an array variable $a into a string of tab separated values. I found a very complete answer by F.Hauri, using IFS, but then I could not make it work in a script. The reason seems to be that using the IFS variable behaves differently in scripts and terminals.
Here is an example (for ease of read, I am using IFS='*' instead of IFS=$'\n'):
a=("0.0 mm" "0.1 mm" "0.3 mm" "0.2 mm")
IFS='*';echo "${a[*]// /'|'}";IFS=$' \t\n';
When I type it directly a bash terminal, I get this output :
0.0|mm*0.1|mm*0.3|mm*0.2|mm
But running the same from a script, yields:
0.0*mm*0.1*mm*0.3*mm*0.2*mm
As you can see, the '*' character is used as separator everywhere when I run this command from a script.
Please help me understand why that happens and how to fix it. Thank you.
(I am running this in Ubuntu 22.04.3 LTS, installed under windows using wls.)
|-separated values- please edit your question to be consistent between your requirements and example.IFSin the code is not safe. It's worse than the problem described in Bash Pitfalls #49 (OIFS="$IFS"; ...; IFS="$OIFS"). There are a few good ways to do what you are trying to do. The accepted answer to How can I convert an array into a comma separated string? has a few of them.