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

www‮al.‬utturi.com
Bash: .* Considered Harmful To Match Dot Files. Why?

In Bash, the .* pattern is often considered harmful when used to match dot files (files that start with a . character). This is because the .* pattern will match not only dot files, but also any other files or directories in the current directory.

For example, if you have the following files in a directory:

.bash_profile
.bashrc
.gitignore
README.md

And you use the .* pattern to try to match the dot files, like this:

for file in .*; do
  echo "$file"
done

This will output the following:

.
..
.bash_profile
.bashrc
.gitignore

As you can see, the .* pattern has matched not only the dot files, but also the . and .. entries, which are the current and parent directories, respectively. This can cause problems if you are trying to operate on only the dot files, as the . and .. entries will be included in the list of matched files.

To avoid this issue, it is recommended to use a more specific pattern when trying to match dot files in Bash. For example, you can use the .??* pattern, which will match only files and directories that start with a . character and have at least two more characters. This will exclude the . and .. entries, while still matching the dot files that you are interested in.

for file in .??*; do
  echo "$file"
done

This will output the following:

.bash_profile
.bashrc
.gitignore

Using a more specific pattern like .??* can help avoid unintended consequences when trying to match dot files in Bash.

Created Time:2017-10-16 14:38:39  Author:lautturi