Convert BASH Array to a Comma Separated List of Values

There's a simple way in bash to add commas between all array elements:

fruits=(apple orange apple)
IFS=, echo "${fruits[*]}"

This will output:

apple,orange,apple

Cool, right? It turns out, the array-to-string expression, ${fruits[*]}, will use the first value of IFS as the separator. That's why the default behaviour of "${fruits[*]}" will be a space separated list, because the first character in default IFS is space.

IFS in front of the (echo) command makes it local to only that command execution.

Code tested on:

$ bash --version
GNU bash, version 5.3.15(1)-release (aarch64-apple-darwin25.4.0)

Happy hacking!


~ /home 🏠 ~ talks 💬 ~ bash ~ craftsmanship ~ db ~ dongxi ~ emacs ~ escenic ~ iam ~ identity ~ java ~ js ~ language ~ latex ~ ldap ~ life ~ linux ~ llm ~ mac-os-x ~ mt-foo ~ network ~ norsk ~ python ~ quotes ~ running ~ security ~ travel ~ unix ~ various ~ vcs ~ webdesign ~ windows ~ discoveries ~ cv 🧙 ~

Licensed under CC BY Creative Commons License ~ 📡 RSS feed ~ ✉ torstein.k.johansen @ gmail ~ 🐘 @skybert@hachyderm.io ~ 🎥 youtube.com/@skybert