Search code examples
gitfilenamesspaces

How to enforce a "no spaces in filenames" policy in git?


As the title says. I want git to refuse to add files which contain spaces in filenames. Is there a config which enforces this?


Solution

  • The regular expression of **\ ** can be used in the .gitignore file for rejecting file names with spaces.

    Here is the demonstration of a working example:

    Step 1: Add **\ ** to .gitignore file in the repository

    $ my-repository (master)
    $ ls
    core/  it.tests/  pom.xml  README.md  ui.apps/  ui.content/
    
    $ cat .gitignore
    **/.classpath
    **/target
    **/node_modules/
    /node_modules/
    /build/
    
    **\ ** 
    
              ---> Ignore file that has blank spaces in the name
    

    Step 2: Create a file with blank spaces in the name (Example: x y z.txt)

    $ echo "Hello! How are you doing?" > "x y z.txt"
    
    $ ls
     core/   it.tests/   pom.xml   README.md   ui.apps/   ui.content/
    
     'x y z.txt'
    

    Step 3: Try to add the file with spaces in name to the repository and commit

    $ git add .
    
    $ git commit -a
    
    On branch master
    Your branch is up to date with 'origin/master'.
    
    nothing to commit, working tree clean
    

    Result:

    The pattern of **\ ** in .gitignore file prevents the file with blank space in its name from being added to the repository.

    More information on .gitignore file:

    https://git-scm.com/docs/gitignore