2

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.

4
  • Helping you : thegeekstuff.com/2010/06/bash-array-tutorial Commented May 2, 2014 at 7:11
  • Can the variable names also differ ? or will they always be like var1, var2 .... ? Commented May 2, 2014 at 7:14
  • 2
    "I do not know if this should be an array or such like" Probably yes. To give you a better answer, you need to explain where the variables are coming from. Commented May 2, 2014 at 7:17
  • As @John1024 said, knowing where the variables are coming from can help; for instance, if they are coming from the command line into a shell script, you could do something similar to the following: val=; for var in "$@"; do val="${val},${var}"; done; echo "${val},$#", then doing something like test.sh a b c d e would output ,a,b,c,d,e,5 (an extra , yeah, but where the variables are coming from might eliminate this, or change the loop completely). Commented May 2, 2014 at 7:26

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.