Bash script to compare two lists

Hi,

I do little bash scripting so sorry for my ignorance.

How do I compare if the two variable not match and if they do not match run a command.

I was thinking a for loop but then I need another for loop for the 2nd list and I do not think that would work as in the real world there could be >= 100 entries in the variables.

$VAR1="me you him her"
$VAR2="you me him"

If VAR2 does not contain an entry in VAR1 create this missing entry and do xyz else do yz.

Given you're using bash, you could store your lists in arrays:

The following output:

zsh-4.3.11[t]% bash s
before ...
me      you
you     me
him     him
her     
after ...
me      me
you     you
him     him
her     her

... is produced by the code below:

list1=(
  me you him her
  )
list2=(
  you me him
  )

printf 'before ...\n'

paste <( printf '%s\n' "${list1[@]}" ) <( printf '%s\n' "${list2[@]}" )  
  
for i in "${!list1[@]}"; do
  [[ ${list1} != ${list2} ]] &&
    list2=${list1}
done

printf 'after ...\n'

paste <( printf '%s\n' "${list1[@]}" ) <( printf '%s\n' "${list2[@]}" ) 

POSIX shell:

VAR1='me you him her'
VAR2='you me him'
for w in $VAR1; do                                                         
  if ! echo "$VAR2" | grep -q "$w" ; then
    changed=1
    VAR2="$VAR2 $w"
  fi
done
if [ "$changed" ]; then
  echo "changed: VAR1='$VAR1' VAR2='$VAR2'"
else
  echo "no changed: VAR1='$VAR1' VAR2='$VAR2'"
fi
1 Like