sathavahana
sathavahana

Reputation: 15

Shell script to check if a directory contains more than 4 files

I need a shell script that checks if a directory contains more than 4 files and change directory owner.

The below script only checks if a directory is empty or not , if the directory is empty it changes the directory owner to lohith and if directory is not empty it changes owner to satha .

Here what needs to be added to script to check if a directory contains more than 4 files it needs to change owner to satha and if directory contains less than 4 files or if directory is empty it needs to change owner to lohith.

#!/bin/bash
FILE=""
DIR="/home/ec2-user/test1"
# init
# look for empty dir 
if [ "$(ls -A $DIR)" ]; then
     chown satha $DIR
else
     chown lohith $DIR
fi

Upvotes: 0

Views: 781

Answers (1)

tjm3772
tjm3772

Reputation: 3154

You generally do not want to parse the output of the ls command in a script. A non-ls example might look like:

#!/bin/bash
dir_files=("$DIR"/*)
if [[ "${#dir_files[@]}" -gt 4 ]] ; then
 #More than 4 files
elif [[ -e "${dir_files[0]}" ]] ; then
 #non-empty
else
 #empty
fi

This puts the list of files in an array, and then checks in order: If the array has more than 4 elements (thus more than 4 files), then checks if the directory is non-empty by confirming the first element of the array exists (which proves the glob matched something), then falls into the final case where the directory was empty.

Upvotes: 6

Related Questions