I have a piece of bash code, in which I would like to make a long string from an array of strings.

The bash code is as follows:

# Load all the SNPs
arrSNPsToBeExtracted=( $( cat $indexFileName ) )


while [ $si -lt $lenArrSNPsToBeExtracted ]

    #echo $si": "${arrSNPsString}

    let si++


echo $arrSNPsString


As you can see, I have a list of SNPs (words):


And I want to make it like this:


This string is assigned to arrSNPsString, but I cannot make it happen. What am I doing wrong?

As you can see in the code, the arrSNPsString should get longer, but instead, it takes at the end of the while loop only the last item.

I know it has something to do with local and global environments/variables. I want to extend a global string arrSNPsString in a local loop.

Does someone know How I can solve this problem

1 Answer 1


I read this in the bash man page:

If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable.

so you could replace your loop by :

arrSNPsString="$(IFS="|"; echo "${arrSNPsToBeExtracted[*]}" )"
echo "$arrSNPsString"

I tried this myself directly at the bash prompt :

a[2]="bbbb cccc"
b="$(IFS="|"; echo "${a[*]}")"
echo "$b"

which prints:

aaaa|bbbb cccc|dddd

Don't mess with IFS, always restore its old value after you have changed it. The $(..) syntax in this code does that for you.

  • Even better, just use IFS for only that command like this: IFS='|' arrSNPsString="${arrSNPsToBeExtracted[*]}" on one line. No need to restore it
    – kiri
    Dec 1, 2013 at 5:14
  • @minerz029 I tried that syntax but it didn't worked. I tried to escape the " and $, I tried to use eval, I tried a mix ... no success. I think that's because second argument arrSNPsString=... is also an assignement,, not a command that will use the IFS value.
    – Emmanuel
    Dec 2, 2013 at 11:02
  • What about arrSNPsString="$(IFS='|' echo "${arrSNPsToBeExtracted[*]}")"?
    – kiri
    Dec 2, 2013 at 20:31
  • @minerz029 good idea to use $(...) solution is : arrSNPsString="$(IFS='|' eval echo \"\${arrSNPsToBeExtracted[*]}\")" or arrSNPsString="$(IFS='|' eval echo '"${arrSNPsToBeExtracted[*]}"')"
    – Emmanuel
    Dec 3, 2013 at 10:48
  • 1
    @minerz029 arrSNPsString="$(IFS='|' ; echo "${arrSNPsToBeExtracted[*]}")" thank you for pointing to separate the two commands.
    – Emmanuel
    Dec 18, 2013 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.