luvprogramin
luvprogramin

Reputation: 3

count files in a script that match the passed in parameter

When I run the following script in bash with no arguments it returns the correct number of files in this directory. But when I call it with *.txt it only returns with 1 (no mannner how many *.txt files there are). How can I get it to correctly expand the *.something in a script?

function files {
    ls -1 --file-type $1 | grep -v '/$' | wc -l
}

Upvotes: 0

Views: 82

Answers (1)

Barmar
Barmar

Reputation: 781210

Wildcards are expanded before calling the function (unless you quote the argument). You should use "$@" to get all the arguments.

function files {
    ls --file-type "$@" | grep -c -v '/$'
}

Other changes:

  1. You don't need -1 when piping the output of ls. When output isn't to a terminal, it defaults to this option.
  2. You don't need to pipe the output of grep to wc -l, you can use the -c option to print the count.

Upvotes: 1

Related Questions