gitmacoszshglob

on macos, git clean <pattern> not working recurcively (like unix)


Under linux, I used to use git clean *.orig, or git clean *.orig *.swp *.swo to clean my repositories while keeping some untracked file.

For example, with the following repo status:

$ git status
composer.json.orig
config/services.yaml.orig

The command git clean *.orig remove composer.json.orig, then if I execute git clean *.orig again, the file config/services.yaml.orig is removed.

However, I now have to work on mac os, and the command doesn't work the same, the subdirectories are not cleaned.

How can I make this works like under unix ?


Solution

  • Unix/Linux shells expand unescaped/unquoted metacharacters like *. When you have files that match wildcard template *.orig in the current directory the shell expands the template to a list of files and pass the list to the command so instead of git clean *.orig the shell executes git clean composer.json.orig. After the file is removed in the next command git clean *.orig the shell doesn't expand *.orig because there are no files in the current directory that match the template so it really executes git clean *.orig and Git expands the template recursively.

    There are two ways to work around that. First, instead of using simple template *.orig you can use *.orig **/*.orig to make the shell expand the template in the current directory and recursively so the shell executes the command git clean composer.json.orig config/services.yaml.orig.

    The second way is forbid the shell to expand the template at all and make it pass the template unchanged/unexpanded to Git so Git works recursively on it. For this either escape the asterisk with a backslash: git clean \*.orig or use single/double quotes: git clean "*.orig". Shells don't expand asterisk templates inside quotes. (The difference between single and double quotes is that shells don't expand anything inside apostrophes/single quotes but expand $environment_variables in double quotes).

    The bottom line is: remember when the shell expands metacharacters and when you want to protect them from expanding.