-1

This question already has an answer here:

Create a script to ask a user for the name of a folder and have the script return the number of files found within the folder. If folder doesn't exist, display error message to the screen

I've gotten the first part of this question completed, and I'm aware that a variable will need to be created to store the num of files found in the folder. I'm just stuck on how to return the number of files found. Any advice on how I would go about doing this? I know the ls command will be used.

clear
echo -e "Option #11: Acquire the number of files within a particular folder\n\n"
echo -e "Enter in the Folder Name below\n"
read foldername
answer=$(grep $foldername)
if [ "$answer" = "" ]
then
clear
echo -e "\n No Such Folder Exists"
else

marked as duplicate by don_crissti, Anthon, cuonglm, Michael Homer, dhag May 6 '15 at 5:34

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

There are a few ways to approach this. The first is using bash arrays:

shopt -s nullglob
if [[ -d $foldername ]]; then
  files=("$foldername"/*)
  answer="${#files[@]}"
else
  printf '%s does not exist\n' "$foldername"
fi

If your shell doesn't support arrays, you can loop at count:

count=0
for f in "$foldername"/*; do
  count=$((count + 1))
done

Another option is to use ls. This is the least reliable method as it doesn't handle all possible filenames:

count=$(( $(ls -al | wc -l) - 2))

You need to subtract 2 as the output of ls -al includes . and ...

  • Thank you so much for your help. jordanm I'm confused as to what you mean by "What shell? Bash?". I'm very new to all of this and am currently in a class called "UNIX Operating System". – Nathan Rampado May 6 '15 at 2:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.