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

Jens
  • 69,818
  • 15
  • 125
  • 179
Rumen Hristov
  • 867
  • 2
  • 13
  • 29

3 Answers3

5

I suggest

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

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

that other guy
  • 116,971
  • 11
  • 170
  • 194
Jens
  • 69,818
  • 15
  • 125
  • 179
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).
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • shopt: command not found; this suffers from "all the worlds a Linux/bash system". – Jens Feb 03 '15 at 07:28
  • `shopt` not found in BASH? – anubhava Feb 03 '15 at 07:30
  • 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. – Jens Feb 03 '15 at 07:38
  • **needless bashisms** is for **[avoiding parsing `ls` command](http://mywiki.wooledge.org/ParsingLs)**. – anubhava Feb 03 '15 at 07:50
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
ALex_hha
  • 1,345
  • 15
  • 16