Add value to end of array

I'm trying to expand my array by adding another value onto the end of it, thus adding a new index and upping the length of the array by one. I am iterating through two arrays, and trying to get one array into the index of the other. I'm use 4.1.5 release of bash and most of the methods I have tried are outdated.

This is my code...

for ((i=1; i<=${COUNT1}; i++))
do
	for ((j=1; j<=${COUNT2}; j++))
	do
		if [[ ${MAIN_ARRAY} != ${SECOND_ARRAY[${j}]} ]]
		then
                      #Put the value of SECOND_ARRAY in MAIN_ARRAY
		fi
	done
done

I originally tried the += method and it did not work.

${ARRAY}+=${NEW_VALUE[${i}]}

Then I tried adding one to the length of the array.

q=`echo ${#ARRAY[@]}`
let q++ 
ARRAY[${q}]=${SECOND_ARRAY[${j}]}

Again, I am trying to iterate through two arrays, and if the the value of the second array is not in the first, put it in there at the end.

That arrays make loops such a pain is one reason I think they're overused.

A1="a b c d e f g"
A2=" q i u d e f g"

for X in $A1
do
        FOUND=0

        for Y in $A2
        do
                [ "$X" = "$Y" ] && FOUND=1
                [ "$FOUND" -gt 0 ] && break
        done

        [ "$FOUND" -eq 0 ] && A1="$A1 $X"
done

But if you must use arrays, that kind of loop works with them too:

for X in "${A1[@]}"
do
        FOUND=0

        for Y in "${A2[@]}"
        do
                [ "$X" = "$Y" ] && FOUND=1
                [ "$FOUND" -gt 0 ] && break
        done

        [ "$FOUND" -eq 0 ] && A1=( "${A1[@]}" $X )
done

One way with recent bash versions:

$ a1=( a b c d ) a2=( c d e f )
$ declare -p a1 a2
declare -a a1='([0]="a" [1]="b" [2]="c" [3]="d")'
declare -a a2='([0]="c" [1]="d" [2]="e" [3]="f")'
$ a1+=($( printf '%s\n' "${a2[@]}" | grep -Fxvf <( printf '%s\n' "${a1[@]}" )))
$ declare -p a1
declare -a a1='([0]="a" [1]="b" [2]="c" [3]="d" [4]="e" [5]="f")'

Values with special characters may need special attention.

P.S. declare -p is used only to display the content of the arrays.

1 Like

I'm new at bash, and do not understand some of your code.

What is the

[..]
[..]

in the for loop?

I'm assuming its like an if? Saying if X=Y then make found=1?

You already know what [ ] do if you've used if-statements before. It's actually an independent thing, if just makes use of it. It returns success when the statement within is true, or error when false.

&& is a short-form if-then. If the thing on the left returns success, run the thing on the right. || is the opposite -- if the thing on the left returns error, run the thing on the right.

true && echo "This will print"
false && echo "But this won't"

true || echo "This will not print"
false || echo "But this will"
1 Like