Home:ALL Converter>Incredibly slow bash loop

Incredibly slow bash loop

Ask Time:2018-06-08T22:10:53         Author:Andy Thompson

Json Formatter

I did a quick thing to just stuff some commands into a function and loop over a file and run it for each line. I am amazed at the slow speed this achieves.

Any suggestions as to how can I speed up this loop which uses the smelly function?

#!/bin/bash
list="lists/test.txt"

smellyfunc() {

alphabet=abcdefghijklmnopqrstuvwxyz
bgam=bcdefghijklmnopqrstuvwxyz
plaintext=THXGAWDITSFRIDAYTODAY
plaintext=$(echo "$plaintext" | tr A-Z a-z | sed s/[^a-z]//g) 
step=0

while test -n "$plaintext"
do
  key=$1
  length=${#key}
  char=${plaintext:0:1}
  shift=${key:$step:1}
  code=$(echo -n $(($(expr index $bgam $char)-$(expr index $bgam $shift))))
  step=$(($(($step+1))%$length))
  if [[ $code -lt 0 ]]
    then
    code=$((code+26))
  fi
  if [[ $code -gt 25 ]]
    then
    code=$((code-26))
  fi
  echo -n ${alphabet:$code:1}
  plaintext=${plaintext:1}
done
}

while read line; do
   key="$line"
   result="$(smellyfunc "$key")"
   echo "$result" "$key"
done < $list

Thanks!

Author:Andy Thompson,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50762544/incredibly-slow-bash-loop
yy