Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

DZone's Guide to

# Shell: Create a Comma Separated String

### In this quick tutorial, we go over how to use Shell scripting in a pinch to create working strings of code that will help us make basic calculations.

· Web Dev Zone ·
Free Resource

Comment (3)

Save
{{ articles[0].views | formatCount}} Views

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

I recently needed to generate a string with comma separated values, based on iterating a range of numbers (e.g. we should get the following output where n = 3).

``foo-0,foo-1,foo-2``

I only had Shell available to me so I couldn’t shell out into Python or Ruby, for example. That means it’s Bash scripting time!

If we want to iterate a range of numbers and print them out on the screen we can write the following code:

``````n=3
for i in \$(seq 0 \$((\$n > 0? \$n-1: 0))); do
echo "foo-\$i"
done

foo-0
foo-1
foo-2``````

Combining them into a string is a bit more tricky, but luckily I found a great blog post by Andreas Haupt which shows what to do. Andreas is solving a more complicated problem than me, but these are the bits of code that we need from the post.

``````n=3
combined=""

for i in \$(seq 0 \$((\$n > 0? \$n-1: 0))); do
token="foo-\$i"
combined="\${combined}\${combined:+,}\$token"
done
echo \$combined

foo-0,foo-1,foo-2``````

This won’t work if you set n<0, but that’s ok for me! I’ll let Andreas explain how it works:

• \${combined:+,} will return either a comma (if combined exists and is set) or nothing at all.
• In the first invocation of the loop combined is not yet set and nothing is put out.
• In the next rounds combined is set and a comma will be put out.

We can see it in action by printing out the value of `\$combined` after each iteration of the loop:

``````n=3
combined=""

for i in \$(seq 0 \$((\$n > 0 ? \$n-1: 0))); do
token="foo-\$i"
combined="\${combined}\${combined:+,}\$token"
echo \$combined
done

foo-0
foo-0,foo-1
foo-0,foo-1,foo-2``````

Looks good to me!

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
bash ,shell ,scripting ,web dev

Comment (3)

Save
{{ articles[0].views | formatCount}} Views

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.