How can I tell whether the current working directory is ignored by Git?

I have a git controlled directory (actually my home directory) within which there are ignored directories (e.g. trash space, and directories controlled by other VCSs). I want to be able to have my bash prompt show whether a directory is version controlled and if so by which VCS, but e.g. git rev-parse will always find the topmost .git directory.

Is there a way to ask git whether I’m in an untracked directory?

  • Bash completion: Honor repository-specific Git alias in alias completion
  • How to make bash suppose all commands to be git commands?
  • How do I get my iTerm prompt to display differently when I'm in a Git branch?
  • Installing bundler within Jenkins docker image
  • Is it possible to pre-evaluate a value in bash's PS1?
  • Can't add a file separated with space to git
  • I’ve found this to work:

    if ! git rev-parse 2>&/dev/null; then
        echo "not in git"
        PREFIX=$(git rev-parse --show-prefix)
        if [ -z "$PREFIX" ]; then
            echo "at git top level"
        elif [ -z $(cd $(git rev-parse --show-toplevel); \
              git ls-files -o --directory "${PREFIX%%/}")
            echo "tracked by git"
            echo "untracked"

    However it seems very hackish and brittle. Is there a better way?

  • Getting started with Version Control
  • Restore files removed by Git checkout
  • How do I see changes in the git index?
  • Authenticating SourceTree with a Google Code project
  • Git Workflow Best practices
  • Merge GIT branch without commit log
  • 2 Solutions collect form web for “How can I tell whether the current working directory is ignored by Git?”

    git clean -nd approach: If it is ignored directory, then git clean -d wants to remove it, so it is easy way to check status of current directory.

    if git clean -xnd `pwd` | grep 'Would remove \./' > /dev/null; then
        echo "Inside ignored or untracked directory"
        echo "Inside normal directory"

    Tweak git clean to change rules about untracked files. Checked in my $HOME repository.

    Note: don’t experiment with git clean without -n lightly, it can clear things from your home.

    You can use bash_completion and a modified PROMPT_COMMAND. It worked for me in casual testing, but if it breaks you own both pieces. 🙂

    # Add this to your shell startup file (e.g. ~/.bashrc).
    export PS1
    export PROMPT_COMMAND='
        if fgrep -q "${PWD/\/home\/$LOGNAME\/}" ~/.gitignore; then
            PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w$(__git_ps1) [ignored]\$ "
            PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w$(__git_ps1)\$ "

    To make this work, you’ll need to make sure all your ignored paths are listed relative to your home directory, and be sure to test it out before relying on it to protect you from any destructive operations like rm -rf.

    Git Baby is a git and github fan, let's start git clone.