Search code examples
bashshellzshoh-my-zsh

Increment Number in ZSH script


I am trying to create directories based off of the number of files I have in a directory and my approach is a loop.

I am keeping track of the number by a number variable and want to increment it as so after each even number, create a directory.

This is my code so far:

#!/bin/zsh

LOOP=$(ls 2021/*.xlsx)
totalFiles=$(ls 2021/*.xlsx | wc -l)
directoryCount=0
count=0

for FILE in ${LOOP[@]}; do
    echo "BEFORE: $count"
    count=$((count+1))
    echo "AFTER: $count"
    echo $FILE
done

echo "TOTAL FILE: $totalFiles"
echo $count

and the output I get is:

BEFORE: 0
AFTER: 1
2021/*Tanner2103.xlsx
2021/*Tanner2104.xlsx
2021/*Tanner2105.xlsx
2021/*Tanner2106.xlsx
TOTAL FILE:       4
1

I dont understand why count only increments once but the loop is obviously has more iterations than that.

So basically since there are 4 files, I want to split them up into 2 directories, Ill do the logic for that later. But for now Im just trying to get the directory code working.


Solution

  • Ok I feel silly. I thought that ls would come back as an iterable but its actual only return one iteration as a whole.

    This is my updated code and it updating like I want.

    totalFiles=$(ls 2021/*.xlsx | wc -l)
    
    count=0
    
    for FILE in 2021/**/*(.); do
        echo "BEFORE $count"
        echo "$FILE"
        ((count++))
        echo "AFTER $count"
    done
    
    echo "TOTAL FILE: $totalFiles"
    echo $count
    
    
    result: 
    BEFORE 0
    2021/*Tanner2103.xlsx
    AFTER 1
    BEFORE 1
    2021/*Tanner2104.xlsx
    AFTER 2
    BEFORE 2
    2021/*Tanner2105.xlsx
    AFTER 3
    BEFORE 3
    2021/*Tanner2106.xlsx
    AFTER 4
    TOTAL FILE:       4
    4