How to remove local (untracked) files from the current Git working tree

前端 未结 30 1905
死守一世寂寞
死守一世寂寞 2020-11-22 00:07

How do you delete untracked local files from your current working tree?

相关标签:
30条回答
  • 2020-11-22 00:49

    Be careful while running `git clean` command.

    Always use -n before running the actual command as it will show you what files would get removed.

    git clean -n -d 
    git clean -f -d
    

    By default, git clean will only remove untracked files that are not ignored. Any file that matches a pattern in your .gitignore or other ignore files will not be removed. If you want to remove those files too, you can add a -x to the clean command.

    git clean -f -d -x
    

    There is also interactive mode available -i with the clean command

    git clean -x -i
    

    Alternatively

    If you are not 100% sure that deleting your uncommitted work is safe, you could use stashing instead

    git stash --all
    

    It will also clear your directory but give you flexibility to retrieve the files at any point in time using stash with apply or pop. Then at later point you could clear your stash using:

    git stash drop // or clean
    
    0 讨论(0)
  • 2020-11-22 00:52

    A lifehack for such situation I just invented and tried (that works perfectly):

    git add .
    git reset --hard HEAD
    

    Beware! Be sure to commit any needed changes (even in non-untracked files) before performing this.

    0 讨论(0)
  • 2020-11-22 00:54

    oh-my-zsh with zsh provides those great aliases via the git plugin. They can be used in bash as well.

    gclean='git clean -fd'
    gpristine='git reset --hard && git clean -dfx'

    • gclean removes untracked directories in addition to untracked files.
    • gpristine hard reset the local changes, remove untracked directories, untracked files and don't use the standard ignore rules read from .gitignore (per directory) and $GIT_DIR/info/exclude, but do still use the ignore rules given with -e options. This allows removing all untracked files, including build products. This can be used (possibly in conjunction with git reset) to create a pristine working directory to test a clean build.
    0 讨论(0)
  • 2020-11-22 00:55

    If needed to remove untracked files from particular subdirectory,

    git clean -f {dir_path}
    

    And combined way to delete untracked dir/files and ignored files.

    git clean -fxd {dir_path}
    

    after this you will have modified files only in git status.

    0 讨论(0)
  • 2020-11-22 00:55

    To remove Untracked files :

    git add .
    git reset --hard HEAD
    
    0 讨论(0)
  • 2020-11-22 00:56

    To know what will be deleted before actually deleting:

    git clean -d -n

    It will output something like:

    Would remove sample.txt

    To delete everything listed in the output of the previous command:

    git clean -d -f

    It will output something like:

    Removing sample.txt

    0 讨论(0)
提交回复
热议问题