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=$' tn';
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.)
2
Answers
It behaves the same way inside or outside of a script:
Outside:
Inside:
If, as you say at the start of your question, you want to:
then all you need is:
Don’t mess with IFS, use
printf
instead:Printf can create vars: