skip to Main Content

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


  1. It behaves the same way inside or outside of a script:

    Outside:

    $ a=("0.0 mm" "0.1 mm" "0.3 mm" "0.2 mm")
    $ IFS='*';echo "${a[*]// /'|'}";IFS=$' tn';
    0.0|mm*0.1|mm*0.3|mm*0.2|mm
    

    Inside:

    $ cat tst.sh
    #!/usr/bin/env bash
    
    a=("0.0 mm" "0.1 mm" "0.3 mm" "0.2 mm")
    IFS='*';echo "${a[*]// /'|'}";IFS=$' tn';
    

    $ ./tst.sh
    0.0|mm*0.1|mm*0.3|mm*0.2|mm
    

    If, as you say at the start of your question, you want to:

    convert an array variable $a into a string of tab separated values

    then all you need is:

    $ a=("0.0 mm" "0.1 mm" "0.3 mm" "0.2 mm")
    $ var=$( IFS=$'t'; echo "${a[*]}" )
    
    $ echo "$var"
    0.0 mm  0.1 mm  0.3 mm  0.2 mm
    
    $ echo "$var" | cat -A
    0.0 mm^I0.1 mm^I0.3 mm^I0.2 mm$
    
    Login or Signup to reply.
  2. Don’t mess with IFS, use printf instead:

    a=("0.0 mm" "0.1 mm" "0.3 mm" "0.2 mm")
    printf '%st' "${a[@]}"
    0.0 mm  0.1 mm  0.3 mm  0.2 mm
    

    Printf can create vars:

    printf -v var '%st' "${a[@]}"
    echo "$var"
    0.0 mm  0.1 mm  0.3 mm  0.2 mm
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search