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

Time:12-18

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

CodePudding user response:

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.

CodePudding user response:

Here is an example that does use ls. wc -l <filename> will return the number of lines in a file, so if we pipe the output of ls to wc, we can get the number of lines in the file. Since $(pwd) gets the current working directory, you can replace it with any other directory.

#!/bin/bash

DIR=$(pwd)

count=$(ls -a $DIR | wc -l)
if (( $count > 4 )); then
     echo "more than four"
else
     echo "less than four"
fi
  • Related