Bash Wildcards – Wildcard Not Expanding Hidden Files

bashwildcards

I'm trying to make a bash script that deals with every file in a directory. All of those file names begin with a dot, so they're hidden. When I try to use a wildcard to grab everything in the directory, the wildcard isn't expanding.

My code that loops over it looks like this right now:

#!/bin/bash
shopt -s extglob

for i in "$(pwd)"/*; do
  echo "$i"
done

The output is just /Users/.../*. The wildcard doesn't expand.

This is different than some of the other threads because it deals with hidden files specifically. If I add a file like test to the directory, then it works. I get /Users/.../test.

I tried running this in the terminal by itself as well and got the same result. How do I get the wildcard to expand for hidden files?

Best Answer

I figured it out! Looking more closely at the documentation for shopt, there's an option called dotglob that can be used to include filenames that begin with a dot!

I added shopt -s dotglob to the beginning of my script and it works now. The output now lists every hidden file and directory (except ./ and ../).

My script now looks like this:

#!/bin/bash
shopt -s extglob
shopt -s dotglob

for i in "$(pwd)"/*; do
  echo "$i"
done
Related Question