aboutsummaryrefslogtreecommitdiff
path: root/bin/cf
blob: d245fec10ad782b9197622838c240fabf1dd3fe7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/bin/sh
# Count entries in a given set of directories
self=cf

# Parse options out
while getopts 'o' opt ; do
    case $opt in

        # Print only the count, not the filename
        o) only=1 ;;

        # Unknown option
        \?)
            printf >&2 '%s: Unknown option %s\n' \
                "$self" "$opt"
            exit 2
            ;;
    esac
done
shift "$((OPTIND-1))"

# Iterate over remaining non-option arguments (directories); default to current
# directory if none given
for dir in "${@:-.}" ; do

    # Warn if a non-directory was given, flag errors, but continue
    if ! [ -d "$dir" ] ; then
        printf >&2 '%s: %s: not a directory\n' \
            "$self" "$dir"
        ex=1
        continue
    fi

    # Add files matching glob, shift them off if unexpanded (first and only
    # entry doesn't exist)
    set -- "$dir"/*
    [ -e "$1" ] || shift

    # Add dot files, shift off the "." and ".." entries (sh(1) implementations
    # seem to vary on whether they include these)
    set -- "$dir"/.* "$@"
    [ -e "$1" ] || shift
    [ "$1" = "$dir"/. ] && shift
    [ "$1" = "$dir"/.. ] && shift

    # Print either just the count, or the count and the dirname
    if [ -n "$only" ] ; then
        printf '%u\n' "$#"
    else
        printf '%u\t%s\n' "$#" "$dir"
    fi
done

# Exit non-zero if a non-directory was given as an argument
exit "${ex:-0}"