Search code examples
fileunixif-statementcountls

IF depending on number of files per folder --unix


I want to do different actions based on the number of files in each folder which start with same two letters --- if files in TS are less than or equal 6 to do one set of actions and otherwise do another set my data looks like this

files/TS01 -- which has 2 files  
files/TS02 -- which has 5 files 
files/TS03 -- which has 2 files 
files/TS04 -- which has 7 files
files/TS05 -- which has 9 files

I have tried

FILES="$TS*"
for W in $FILES
do
    doc=$(basename $W) 
    if [ $W -le 6 ] 
    then
    ....
    done ...
    fi
done

but I get an error saying "integer expression expected"

I have tried to

if [ ls $W -le 6 ] 

I get another erros saying "too many arguments"

Can you please help


Solution

  • To get the number of lines I would recomend piping ls -l into wc -l, this will spit out the number of lines in your directory as follows...

    Atlas $ ls -l | wc -l
        19
    

    I've made a small script which shows how you could then use this result to conditionally do one thing or another...

    #!/bin/bash
    
    amount=$(ls -l | wc -l)
    
    if [ $amount -le 5 ]; then
        echo -n "There aren't that many files, only "
    else
        echo -n "There are a lot of files, "
    fi
    
    echo $amount
    

    When executed on a folder with 19 files it echoes..

    Atlas $ ./howManyFiles.sh
        There are a lot of files, 19
    

    and on one with less then 5 files...

    Atlas $ ./howManyFiles.sh
        There aren't that many files, only 3
    

    Hopefully this helps show you how to get a useable file count from a folder, and then how to use those results in an "if" statement!