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?

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?

  • Git ignore not ignoring one file, but all files
  • Gitignore multiple project
  • How to remove distant folders added to .gitignore
  • Git add . failing on subdirectory that has a .git folder, even though being ignored
  • Confusion on gitignore file tracking
  • How to reliably check whether a file is ignored by git?
  • How to I add something to the .gitignore so that the match is not recursive?
  • .gitignore doesn't ignore files in subdirectories
  • 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.