1

I need to print the contents of my associative array to a file in bash.. The console output printing is working fine but when I try to print it to a file, only one element is getting printed. Here is my code

 for KEY in "${!SYMBOLICLINK[@]}"; do
    printf "$KEY --> ${SYMBOLICLINK[$KEY]}" > /tmp/symlinks.txt
     # Print the KEY value
     echo " $KEY --> ${SYMBOLICLINK[$KEY]}"
      done   

Can someone pls tell me what i am missing here

I also went through this

BASH associative array printing

but it didn't help

achak01
  • 21

1 Answers1

2

This is where it's not working for you:

printf "$KEY --> ${SYMBOLICLINK[$KEY]}" > /tmp/symlinks.txt

The > redirection overwrites the file. You want >>, to append.

Overall, I would write your code like this, to improve safety, readability and performance:

for KEY in "${!SYMBOLICLINK[@]}"; do
    printf "%s --> %s\n" "$KEY" "${SYMBOLICLINK[$KEY]}"
done | tee /tmp/symlinks.txt

Reasons:

cryptarch
  • 1,270