-1

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 
2

1 Answer 1

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 ...

1
  • 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". Commented May 6, 2015 at 2:30

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.