user3400057
user3400057

Reputation: 21

Create array from many variables

Using bash I am trying to create an echo command with a list of variables. The number of variables can differ on what I am trying to do but I know how many I have as I count them in $ctr1. An example of what it should look like is:

echo "$var1,$var2,$var3"

etc. with the last variable the same number as the counter.

Can someone give me an idea as to what I should be doing, an example would be great. I know it could be done with if statements with a line for the possible number in the counter but that is not practical as there can be from 1 to 50+ variables in a line. I do not know if this should be an array or such like nor how to put this together. Any assistance on this would be a help.

Upvotes: 2

Views: 97

Answers (1)

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45536

Yes, this should be an array instead.

Instead of doing e.g.

var1=foo
var2=bar
var3=quux
ctr1=3
echo "${var1},${var2},${var3}"

you could do

var=("foo" "bar" "quux")
( IFS=,; echo "${var[*]}" )

Example:

$ cat test.sh
#!/bin/bash

# the following is equivalent to doing
#  ( IFS=,; echo "$*" )
# but that wouldn't be a good example, would it?

for argument in "$@"; do
    var+=( "${argument}" )
done
( IFS=,; echo "${var[*]}" )

.

$ ./test.sh foo
foo

$ ./test.sh foo bar
foo,bar

$ ./test.sh foo bar "qu ux"
foo,bar,qu ux

Upvotes: 2

Related Questions