Skip to main content
4 of 4
added obligatory "don't do this" warning
steeldriver
  • 83.9k
  • 12
  • 124
  • 175

Before considering doing it this way, please see Why is using a shell loop to process text considered bad practice?

Nevertheless, your attempt is close (one obvious issue is the whitespace around the = in your total_length assignment).

#!/bin/bash

sum=0
while IFS=, read -a fields; do
  if [[ ${fields[12]} = "$1" ]]; then
    (( sum += fields[5] ))
  fi
done < file.csv

printf 'sum: %d\n' "$sum"

You can shorten the if..then..fi using short-scircuit logic if you prefer ex.

[[ ${fields[12]} = "$1" ]] && (( sum += fields[5] ))

There's no need to skip the header line explicitly since it will fail the ${fields[12]} = "$1" test.

steeldriver
  • 83.9k
  • 12
  • 124
  • 175