Home > Mobile >  Running ls with wildcard string
Running ls with wildcard string

Time:09-27

I was originally using this command, and it works fine (counting number of files with extension .sb):

ls -dq *.sb | wc -l

Output:

903

Now, I want to use a variable to store the string, like this:

search="*.sb"

Then, putting it all together:

# count files in directory with substring
search="*.sb"
ls -dq "$search" | wc -l

Output:

ls: cannot access *.sb: No such file or directory
0

This implies the string is being stored and retrieved correctly, but the command is not acting as expected. Could anyone explain this phenomenon to me?

CodePudding user response:

Variable expansion is done before pathname expansion. See here for a similar situation.

Solution in this case: remove the quotation marks

search="*.sb"
ls -dq $search | wc -l
  •  Tags:  
  • bash
  • Related