4

I am trying to output the number of directories in a given path on a SINGLE line. My desire is to output this:

X-many directories

Currently, with my bash sript, I get this:

X-many

directories

Here's my code:

ARGUMENT=$1

ls -l $ARGUMENT | egrep -c '^drwx'; echo -n "directories"

How can I fix my output? Thanks

3 Answers 3

5

I suggest

 echo "$(ls -l "$ARGUMENT" | egrep -c '^drwx') directories"

This uses the shell's feature of final newline removal for command substitution.

Sign up to request clarification or add additional context in comments.

Comments

3

Do not pipe to ls output and count directories as you can get wrong results if special characters have been used in file/directory names.

To count directories use:

shopt -s nullglob
arr=( "$ARGUMENT"/*/ )
echo "${#arr[@]} directories"
  • / at the end of glob will make sure to match only directories in "$ARGUMENT" path.
  • shopt -s nullglob is to make sure to return empty results if glob pattern fails (no directory in given argument).

4 Comments

shopt: command not found; this suffers from "all the worlds a Linux/bash system".
shopt not found in BASH?
Is it so hard to make this simple task work for any shell? Why the needless bashisms? I believe in teaching portability early on and avoiding solutions only working for a limited set of systems.
needless bashisms is for avoiding parsing ls command.
0

as alternative solution

$ bc <<< "$(find /etc -maxdepth 1 -type d | wc -l)-1"
116

another one

$ count=0; while read curr_line; do count=$((count+1)); done < <(ls -l ~/etc | grep ^d); echo ${count}
116

Would work correctly with spaces in the folder name

$ ls -la
total 20
drwxrwxr-x  5 alex alex 4096 Jun 30 18:40 .
drwxr-xr-x 11 alex alex 4096 Jun 30 16:41 ..
drwxrwxr-x  2 alex alex 4096 Jun 30 16:43 asdasd
drwxrwxr-x  2 alex alex 4096 Jun 30 16:43 dfgerte
drwxrwxr-x  2 alex alex 4096 Jun 30 16:43 somefoler with_space

$ count=0; while read curr_line; do count=$((count+1)); done < <(ls -l ./ | grep ^d); echo ${count}
3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.