Bash: .* Considered Harmful To Match Dot Files. Why?

In shell scripts, using the pattern .* to match dot files (files with names starting with a dot) is considered harmful because it may include unexpected files in the match. This is because .* matches any character zero or more times, including the / character. As a result, the pattern will match hidden files and directories in the current directory and any subdirectories. (championshipmartialarts.com)

For example, consider the following directory structure:

.
└── dir
└── .hidden

If you use the pattern .* to match files in the current directory, it will also match the hidden directory ./dir/.hidden, which may lead to unexpected results.

A safer approach to match dot files is to use the pattern .[^/]*. This pattern matches only files in the current directory that start with a dot, but not directories that contain dots in their name.

For example, the following command will match only the dot files in the current directory:

ls -d .[^/]*

Leave a Comment