In: Computer Science
write a bash shell script using the for-loop construct that counts the number of files and directories looping through the files in the directory name provided by the user on a prompt by the script and prints "TOO many files" is the count of files is larger than a random number it generates between 20 and 40
Explanation:
Steps to be followed
1)Create a script by name forloop.sh which consists of a for-loop construct that counts the number of files and directories.
2)Take the directory name as input from the user in the following manner:
sh forloop.sh <directoryname>
where directoryname is the input that will be entered by the user.
3)Declare two variables filecount and dircount to hold the value of the no of files and directories.
4)Declare a variable LOCATION which will store the input entered by the user.
5)Loop through the directory name provided in Step 2.The below command will recursively iterate through the files in the given directory and will increment the count of files and directories present respectively.
for item in $LOCATION/* $LOCATION/.*
do
if [ -f "$item" ]
then
FILECOUNT=$[$FILECOUNT+1]
elif [ -d "$item" ]
then
DIRCOUNT=$[$DIRCOUNT+1]
fi
6)Make use of the command shuf -i 20-40 -n 1 to generate random numbers between 20 and 40 and store it in a variable randomno.
7)Check whether the no of files present in the directory provided in the Step 2 is greater than the random no generated.If the above condition is true print TOO Many Files
Commands to check for the condition in the Step 7 is:
if [ $FILECOUNT -gt $randomno ]
then
echo "TOO Many Files"
exit
fi
8)Display a proper message to the user providing information about the usage of the shell script by using the following commands
if [ "$#" -lt "1" ]
then
echo "Usage: ./forloop.sh <directory>"
exit 0
fi
9)Also we can display the no of file count,dir count and random number count using the following commands
echo "Random Number : $randomno"
echo "File Count" : $FILECOUNT
echo "DIR COUNT" : $DIRCOUNT
NOTE : Above commands are only for informative purpose.They are optional.
10)I have created a test directory with around 32 files in order to test the shells script
--------------------------------------
Content of forloop.sh
LOCATION=$1
FILECOUNT=0
DIRCOUNT=0
if [ "$#" -lt "1" ]
then
echo "Usage: ./forloop.sh <directory>"
exit 0
fi
for item in $LOCATION/* $LOCATION/.*
do
if [ -f "$item" ]
then
FILECOUNT=$[$FILECOUNT+1]
elif [ -d "$item" ]
then
DIRCOUNT=$[$DIRCOUNT+1]
fi
done
randomno=`shuf -i 20-40 -n 1`
echo "Random Number : $randomno"
echo "File Count" : $FILECOUNT
echo "DIR COUNT" : $DIRCOUNT
if [ $FILECOUNT -gt $randomno ]
then
echo "TOO Many Files"
exit
fi
------------------------
Output: No of Files in the directory is not greater than the random number
Output:No of Files in the directory is not greater than the random number