Write a shell script that consists of a function that displays the number of files in the present working directory, but not subdirectories


# Function to count files in the pwd excluding sub directories 
files_in_pwd() {
    num_files=$(ls -l | wc -l) |  -maxdepth 1
    echo "Number of files in the pwd: $num_files"
}

# Call the function
files_in_pwd

 

2

There are 2 best solutions below

3
Barmar On

Use find with the -type f option to count only regular files, and -maxdepth 1 to prevent going into subdirectories.

files_in_pwd() {
    num_files=$(find . -maxdepth 1 -type f | wc -l)
    echo "Number of files in the pwd: $num_files"
}
6
jhnc On
files_in_pwd()(
    shopt -s nullglob dotglob
    any=( * )
    dirs=( */ )
    notdir_count=$(( ${#any[@]} - ${#dirs[@]} ))

    echo "Number of files in the pwd: $notdir_count"
)
files_in_pwd()(
    shopt -s nullglob dotglob
    n=0
    for e in *; do
        # add appropriate extra tests
        if [[ ! -d $e ]]; then
            (( n++ ))
        fi
    done
    echo "Number of files in the pwd: $n"
)