0

So I need to loop through two arrays in bash to find the difference between the two (so if there was an array with a value of 1, 2, 3 and another with a value of 1, 2, 3, 4 it would return a new array with a value of 4). In order too do this I need to somehow 1) find the length of an array, and 2) make an if statement that can add or operators based on the length of the array. How would I do this?

  • Does this answer your question? [Compare/Difference of two arrays in Bash](https://stackoverflow.com/questions/2312762/compare-difference-of-two-arrays-in-bash) – thanasisp Sep 27 '20 at 17:54
  • To be honest, I can't tell what you want, I'd have to guess. Try making a list of steps that don't require interpretation, so that anyone can perform them without having to guess your intention. Then, write the according code for your shell. – Ulrich Eckhardt Sep 27 '20 at 21:23

1 Answers1

1

You may able to do that with process substitution like

#!/bin/bash

a=(1 2 3)

b=(1 2 3 4 5)

c=($(comm -13 <(printf "%s\n" "${a[@]}" | sort) <(printf "%s\n" "${b[@]}" | sort)))
# or 'readarray -t c <<< "$(comm -13 <(printf "%s\n" "${a[@]}" | sort) <(printf "%s\n" "${b[@]}" | sort))"'

echo "${c[@]}"
Rfroes87
  • 668
  • 1
  • 5
  • 15
  • I know that this is a lot to ask, but would you be willing to explain this command by command? I am new to bash and this just looks like gibberish to me. – hufflegamer123 Sep 27 '20 at 20:30
  • In the first lines I'm just assigning the arrays `a` and `b`; `c` is also set as an array resulted from the [`comm`](https://linux.die.net/man/1/comm) subshell command, which I'm concatenating with 2 [process substitution](https://tldp.org/LDP/abs/html/process-sub.html) parameters for redirecting the `a` and `b` arrays to `comm`'s *stdin* (instead of regular files, which are normally used with `comm`). – Rfroes87 Sep 27 '20 at 20:40
  • Thanks, that really helps. – hufflegamer123 Sep 27 '20 at 22:49