4

I want to add the values to a variable, separated by comma, using for loop. First values should remain first and so on.

for ((i=0; i<${#MYARRAY[@]}; i++));
do
  ALL=$ALL$MYARRAY$i,
done
echo $ALL

I expect the output val1,val2,val3 but the actuel output is val1,val2,val3,

How to avoid the comma after the last value?

2
  • Welcome to Stackoverflow. You could add a condition for the 1st iteration : if first => add without comma, else => add with comma before the value. Commented Jun 14, 2019 at 9:53
  • Your string concatenation includes an apparent attempt to include array values, but the form of the array reference is incorrect. Also, you should use lowercase or mixed case variables to avoid possible name collision between them and shell and environment variables. Also, you can use +=. Here is all that combined: all+=${myarray[$i]}, and you should always quote your variables: echo "$all" Commented Jun 14, 2019 at 20:52

5 Answers 5

3

Just add one of the three statements after your for loop:

  1. ALL=${ALL%,}

  2. ALL=${ALL::-1}

  3. ALL=${ALL%?}

Sign up to request clarification or add additional context in comments.

Comments

1

https://www.tldp.org/LDP/abs/html/string-manipulation.html is a good source. Insert the following line after the loop.

ALL=${ALL%,}

1 Comment

Thae LDP/abs is generally low quality.
1

Another option is with the translate (tr) command. For example:

$ myarray=(val1 val2 val3 val4)

$ echo ${myarray[*]}
val1 val2 val3 val4

$ myarray=$(echo ${myarray[*]} | tr ' ' ,)     # Replace space with ','

$ echo $myarray                                # Gives what you need
val1,val2,val3,val4

Comments

0

In this example, the first iteration does not put a comma in $ALL. In the following iteration, a comma is placed before the value. This way, there won't be any comma at the end of the output string.

MYARRAY=(val val val)
for (( i=0; i<${#MYARRAY[@]}; i++ ))
do
    if [ $i == 0 ]
    then
        ALL=$ALL$MYARRAY$i
    else
        ALL=$ALL,$MYARRAY$i
    fi
done
echo $ALL

Comments

0

This is exactly what the [*] construct is for:

myarray=(val1 val2 val3 val4)

oldIFS="$IFS"

IFS=',' 
echo "${myarray[*]}"

IFS="$oldIFS"

gives:

val1,val2,val3,val4

I am using lowercase myarray because uppercase should be reserved for system (bash) variables.

Note that "${myarray[*]}" must be inside double-quotes, otherwise you do not get the join magic. The elements are joined by the first character of IFS, which by default is a space.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.