Search code examples
bashinfinite-loop

Infinite while-loop in BASH script


I'm really struggling to see why this while-loop never ends, when the loop starts, my variable LOC is set to Testing/, which is a directory I created to test this program, it has the following layout:

Layout of my Testing Directory

I want the loop to end once all Directories have had the "count" function applied to them.
Here are the things I have tried;

I've checked my count function, and it doesn't produce an infinite loop

I've tried running through the algorithm by hand

PARSE=1
LOC=$LOC/
count
AVAILABLEDIR=$(ls $LOC -AFl | sed "1 d" |  grep "/$" | awk '{ print $9 }')
while [ $PARSE = "1" ]
do

if [[ ${AVAILABLEDIR[@]} == '' ]]; then
    PARSE=0
fi

DIRBASE=$LOC

for a in ${AVAILABLEDIR[@]}; do
LOC="${DIRBASE}${a}"
LOCLIST="$LOCLIST $LOC"
count
done

for a in ${LOCLIST[@]}; do
TMPAVAILABLEDIR=$(ls $a -AFl | sed "1 d" |  grep "/$" | awk '{ print $9 }')
PREPEND=$a
if [[ ${TMPAVAILABLEDIR[@]} == '' ]]; then
    continue
fi

for a in ${TMPAVAILABLEDIR[@]}; do
    TMPAVAILABLEDIR2="$TMPAVAILABLEDIR2 ${PREPEND[@]}${a}"
done

NEWAVAILABLEDIR="$NEWAVAILABLEDIR $TMPAVAILABLEDIR2"
done

AVAILABLEDIR=$NEWAVAILABLEDIR
NEWAVAILABLEDIR=''
LOC=''
done

I am really struggling, and any input would be greatly appreciated, I've been trying to figure this out for the last couple of hours.


Solution

  • You should try to run the script with argument -x, or write it into the first line:

    #!/bin/bash -x
    

    Then it tells you everything it does.

    In that case, you might notice two errors:

    1. You never reset TMPAVAILABLEDIR2

    2. You do ls on regular files as well.