{
    "mode": "man",
    "parameter": "git-for-each-ref",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/git-for-each-ref/1/json",
    "generated": "2026-06-15T14:37:50Z",
    "synopsis": "git for-each-ref [--count=<count>] [--shell|--perl|--python|--tcl]\n[(--sort=<key>)...] [--format=<format>] [<pattern>...]\n[--points-at=<object>]\n[--merged[=<object>]] [--no-merged[=<object>]]\n[--contains[=<object>]] [--no-contains[=<object>]]",
    "sections": {
        "NAME": {
            "content": "git-for-each-ref - Output information on each ref\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "git for-each-ref [--count=<count>] [--shell|--perl|--python|--tcl]\n[(--sort=<key>)...] [--format=<format>] [<pattern>...]\n[--points-at=<object>]\n[--merged[=<object>]] [--no-merged[=<object>]]\n[--contains[=<object>]] [--no-contains[=<object>]]\n\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "Iterate over all refs that match <pattern> and show them according to the given <format>,\nafter sorting them according to the given set of <key>. If <count> is given, stop after\nshowing that many refs. The interpolated values in <format> can optionally be quoted as\nstring literals in the specified host language allowing their direct evaluation in that\nlanguage.\n",
            "subsections": []
        },
        "OPTIONS": {
            "content": "<pattern>...\nIf one or more patterns are given, only refs are shown that match against at least one\npattern, either using fnmatch(3) or literally, in the latter case matching completely or\nfrom the beginning up to a slash.\n\n--count=<count>\nBy default the command shows all refs that match <pattern>. This option makes it stop\nafter showing that many refs.\n\n--sort=<key>\nA field name to sort on. Prefix - to sort in descending order of the value. When\nunspecified, refname is used. You may use the --sort=<key> option multiple times, in\nwhich case the last key becomes the primary key.\n\n--format=<format>\nA string that interpolates %(fieldname) from a ref being shown and the object it points\nat. If fieldname is prefixed with an asterisk (*) and the ref points at a tag object, use\nthe value for the field in the object which the tag object refers to (instead of the\nfield in the tag object). When unspecified, <format> defaults to %(objectname) SPC\n%(objecttype) TAB %(refname). It also interpolates %% to %, and %xx where xx are hex\ndigits interpolates to character with hex code xx; for example %00 interpolates to \\0\n(NUL), %09 to \\t (TAB) and %0a to \\n (LF).\n\n--color[=<when>]\nRespect any colors specified in the --format option. The <when> field must be one of\nalways, never, or auto (if <when> is absent, behave as if always was given).\n",
            "subsections": [
                {
                    "name": "--shell, --perl, --python, --tcl",
                    "content": "If given, strings that substitute %(fieldname) placeholders are quoted as string literals\nsuitable for the specified host language. This is meant to produce a scriptlet that can\ndirectly be `eval`ed.\n\n--points-at=<object>\nOnly list refs which points at the given object.\n\n--merged[=<object>]\nOnly list refs whose tips are reachable from the specified commit (HEAD if not\nspecified).\n\n--no-merged[=<object>]\nOnly list refs whose tips are not reachable from the specified commit (HEAD if not\nspecified).\n\n--contains[=<object>]\nOnly list refs which contain the specified commit (HEAD if not specified).\n\n--no-contains[=<object>]\nOnly list refs which don’t contain the specified commit (HEAD if not specified).\n",
                    "long": "--tcl"
                },
                {
                    "name": "--ignore-case",
                    "content": "Sorting and filtering refs are case insensitive.\n",
                    "long": "--ignore-case"
                }
            ]
        },
        "FIELD NAMES": {
            "content": "Various values from structured fields in referenced objects can be used to interpolate into\nthe resulting output, or as sort keys.\n\nFor all objects, the following names can be used:\n\nrefname\nThe name of the ref (the part after $GITDIR/). For a non-ambiguous short name of the ref\nappend :short. The option core.warnAmbiguousRefs is used to select the strict\nabbreviation mode. If lstrip=<N> (rstrip=<N>) is appended, strips <N> slash-separated\npath components from the front (back) of the refname (e.g.  %(refname:lstrip=2) turns\nrefs/tags/foo into foo and %(refname:rstrip=2) turns refs/tags/foo into refs). If <N> is\na negative number, strip as many path components as necessary from the specified end to\nleave -<N> path components (e.g.  %(refname:lstrip=-2) turns refs/tags/foo into tags/foo\nand %(refname:rstrip=-1) turns refs/tags/foo into refs). When the ref does not have\nenough components, the result becomes an empty string if stripping with positive <N>, or\nit becomes the full refname if stripping with negative <N>. Neither is an error.\n\nstrip can be used as a synonym to lstrip.\n\nobjecttype\nThe type of the object (blob, tree, commit, tag).\n\nobjectsize\nThe size of the object (the same as git cat-file -s reports). Append :disk to get the\nsize, in bytes, that the object takes up on disk. See the note about on-disk sizes in the\nCAVEATS section below.\n\nobjectname\nThe object name (aka SHA-1). For a non-ambiguous abbreviation of the object name append\n:short. For an abbreviation of the object name with desired length append\n:short=<length>, where the minimum length is MINIMUMABBREV. The length may be exceeded\nto ensure unique object names.\n\ndeltabase\nThis expands to the object name of the delta base for the given object, if it is stored\nas a delta. Otherwise it expands to the null object name (all zeroes).\n\nupstream\nThe name of a local ref which can be considered “upstream” from the displayed ref.\nRespects :short, :lstrip and :rstrip in the same way as refname above. Additionally\nrespects :track to show \"[ahead N, behind M]\" and :trackshort to show the terse version:\n\">\" (ahead), \"<\" (behind), \"<>\" (ahead and behind), or \"=\" (in sync).  :track also prints\n\"[gone]\" whenever unknown upstream ref is encountered. Append :track,nobracket to show\ntracking information without brackets (i.e \"ahead N, behind M\").\n\nFor any remote-tracking branch %(upstream), %(upstream:remotename) and\n%(upstream:remoteref) refer to the name of the remote and the name of the tracked remote\nref, respectively. In other words, the remote-tracking branch can be updated explicitly\nand individually by using the refspec %(upstream:remoteref):%(upstream) to fetch from\n%(upstream:remotename).\n\nHas no effect if the ref does not have tracking information associated with it. All the\noptions apart from nobracket are mutually exclusive, but if used together the last option\nis selected.\n\npush\nThe name of a local ref which represents the @{push} location for the displayed ref.\nRespects :short, :lstrip, :rstrip, :track, :trackshort, :remotename, and :remoteref\noptions as upstream does. Produces an empty string if no @{push} ref is configured.\n\nHEAD\n* if HEAD matches current ref (the checked out branch), ' ' otherwise.\n\ncolor\nChange output color. Followed by :<colorname>, where color names are described under\nValues in the \"CONFIGURATION FILE\" section of git-config(1). For example, %(color:bold\nred).\n\nalign\nLeft-, middle-, or right-align the content between %(align:...) and %(end). The \"align:\"\nis followed by width=<width> and position=<position> in any order separated by a comma,\nwhere the <position> is either left, right or middle, default being left and <width> is\nthe total length of the content with alignment. For brevity, the \"width=\" and/or\n\"position=\" prefixes may be omitted, and bare <width> and <position> used instead. For\ninstance, %(align:<width>,<position>). If the contents length is more than the width then\nno alignment is performed. If used with --quote everything in between %(align:...) and\n%(end) is quoted, but if nested then only the topmost level performs quoting.\n\nif\nUsed as %(if)...%(then)...%(end) or %(if)...%(then)...%(else)...%(end). If there is an\natom with value or string literal after the %(if) then everything after the %(then) is\nprinted, else if the %(else) atom is used, then everything after %(else) is printed. We\nignore space when evaluating the string before %(then), this is useful when we use the\n%(HEAD) atom which prints either \"*\" or \" \" and we want to apply the if condition only on\nthe HEAD ref. Append \":equals=<string>\" or \":notequals=<string>\" to compare the value\nbetween the %(if:...) and %(then) atoms with the given string.\n\nsymref\nThe ref which the given symbolic ref refers to. If not a symbolic ref, nothing is\nprinted. Respects the :short, :lstrip and :rstrip options in the same way as refname\nabove.\n\nworktreepath\nThe absolute path to the worktree in which the ref is checked out, if it is checked out\nin any linked worktree. Empty string otherwise.\n\nIn addition to the above, for commit and tag objects, the header field names (tree, parent,\nobject, type, and tag) can be used to specify the value in the header field. Fields tree and\nparent can also be used with modifier :short and :short=<length> just like objectname.\n\nFor commit and tag objects, the special creatordate and creator fields will correspond to the\nappropriate date or name-email-date tuple from the committer or tagger fields depending on\nthe object type. These are intended for working on a mix of annotated and lightweight tags.\n\nFields that have name-email-date tuple as its value (author, committer, and tagger) can be\nsuffixed with name, email, and date to extract the named component. For email fields\n(authoremail, committeremail and taggeremail), :trim can be appended to get the email without\nangle brackets, and :localpart to get the part before the @ symbol out of the trimmed email.\n\nThe raw data in an object is raw.\n\nraw:size\nThe raw data size of the object.\n\nNote that --format=%(raw) can not be used with --python, --shell, --tcl, because such\nlanguage may not support arbitrary binary data in their string variable type.\n\nThe message in a commit or a tag object is contents, from which contents:<part> can be used\nto extract various parts out of:\n\ncontents:size\nThe size in bytes of the commit or tag message.\n\ncontents:subject\nThe first paragraph of the message, which typically is a single line, is taken as the\n\"subject\" of the commit or the tag message. Instead of contents:subject, field subject\ncan also be used to obtain same results.  :sanitize can be appended to subject for\nsubject line suitable for filename.\n\ncontents:body\nThe remainder of the commit or the tag message that follows the \"subject\".\n\ncontents:signature\nThe optional GPG signature of the tag.\n\ncontents:lines=N\nThe first N lines of the message.\n\nAdditionally, the trailers as interpreted by git-interpret-trailers(1) are obtained as\ntrailers[:options] (or by using the historical alias contents:trailers[:options]). For valid\n[:option] values see trailers section of git-log(1).\n\nFor sorting purposes, fields with numeric values sort in numeric order (objectsize,\nauthordate, committerdate, creatordate, taggerdate). All other fields are used to sort in\ntheir byte-value order.\n\nThere is also an option to sort by versions, this can be done by using the fieldname\nversion:refname or its alias v:refname.\n\nIn any case, a field name that refers to a field inapplicable to the object referred by the\nref does not cause an error. It returns an empty string instead.\n\nAs a special case for the date-type fields, you may specify a format for the date by adding :\nfollowed by date format name (see the values the --date option to git-rev-list(1) takes).\n\nSome atoms like %(align) and %(if) always require a matching %(end). We call them \"opening\natoms\" and sometimes denote them as %($open).\n\nWhen a scripting language specific quoting is in effect, everything between a top-level\nopening atom and its matching %(end) is evaluated according to the semantics of the opening\natom and only its result from the top-level is quoted.\n",
            "subsections": []
        },
        "EXAMPLES": {
            "content": "An example directly producing formatted text. Show the most recent 3 tagged commits:\n\n#!/bin/sh\n\ngit for-each-ref --count=3 --sort='-*authordate' \\\n--format='From: %(*authorname) %(*authoremail)\nSubject: %(*subject)\nDate: %(*authordate)\nRef: %(*refname)\n\n%(*body)\n' 'refs/tags'\n\n\nA simple example showing the use of shell eval on the output, demonstrating the use of\n--shell. List the prefixes of all heads:\n\n#!/bin/sh\n\ngit for-each-ref --shell --format=\"ref=%(refname)\" refs/heads | \\\nwhile read entry\ndo\neval \"$entry\"\necho `dirname $ref`\ndone\n\n\nA bit more elaborate report on tags, demonstrating that the format may be an entire script:\n\n#!/bin/sh\n\nfmt='\nr=%(refname)\nt=%(*objecttype)\nT=${r#refs/tags/}\n\no=%(*objectname)\nn=%(*authorname)\ne=%(*authoremail)\ns=%(*subject)\nd=%(*authordate)\nb=%(*body)\n\nkind=Tag\nif test \"z$t\" = z\nthen\n# could be a lightweight tag\nt=%(objecttype)\nkind=\"Lightweight tag\"\no=%(objectname)\nn=%(authorname)\ne=%(authoremail)\ns=%(subject)\nd=%(authordate)\nb=%(body)\nfi\necho \"$kind $T points at a $t object $o\"\nif test \"z$t\" = zcommit\nthen\necho \"The commit was authored by $n $e\nat $d, and titled\n\n$s\n\nIts message reads as:\n\"\necho \"$b\" | sed -e \"s/^/    /\"\necho\nfi\n'\n\neval=`git for-each-ref --shell --format=\"$fmt\" \\\n--sort='*objecttype' \\\n--sort=-taggerdate \\\nrefs/tags`\neval \"$eval\"\n\n\nAn example to show the usage of %(if)...%(then)...%(else)...%(end). This prefixes the current\nbranch with a star.\n\ngit for-each-ref --format=\"%(if)%(HEAD)%(then)* %(else)  %(end)%(refname:short)\" refs/heads/\n\n\nAn example to show the usage of %(if)...%(then)...%(end). This prints the authorname, if\npresent.\n\ngit for-each-ref --format=\"%(refname)%(if)%(authorname)%(then) Authored by: %(authorname)%(end)\"\n\n",
            "subsections": []
        },
        "CAVEATS": {
            "content": "Note that the sizes of objects on disk are reported accurately, but care should be taken in\ndrawing conclusions about which refs or objects are responsible for disk usage. The size of a\npacked non-delta object may be much larger than the size of objects which delta against it,\nbut the choice of which object is the base and which is the delta is arbitrary and is subject\nto change during a repack.\n\nNote also that multiple copies of an object may be present in the object database; in this\ncase, it is undefined which copy’s size or delta base will be reported.\n",
            "subsections": []
        },
        "NOTES": {
            "content": "When combining multiple --contains and --no-contains filters, only references that contain at\nleast one of the --contains commits and contain none of the --no-contains commits are shown.\n\nWhen combining multiple --merged and --no-merged filters, only references that are reachable\nfrom at least one of the --merged commits and from none of the --no-merged commits are shown.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "git-show-ref(1)\n",
            "subsections": []
        },
        "GIT": {
            "content": "Part of the git(1) suite\n\n\n\nGit 2.34.1                                   02/26/2026                          GIT-FOR-EACH-REF(1)",
            "subsections": []
        }
    },
    "summary": "git-for-each-ref - Output information on each ref",
    "flags": [
        {
            "flag": "",
            "long": "--tcl",
            "arg": null,
            "description": "If given, strings that substitute %(fieldname) placeholders are quoted as string literals suitable for the specified host language. This is meant to produce a scriptlet that can directly be `eval`ed. --points-at=<object> Only list refs which points at the given object. --merged[=<object>] Only list refs whose tips are reachable from the specified commit (HEAD if not specified). --no-merged[=<object>] Only list refs whose tips are not reachable from the specified commit (HEAD if not specified). --contains[=<object>] Only list refs which contain the specified commit (HEAD if not specified). --no-contains[=<object>] Only list refs which don’t contain the specified commit (HEAD if not specified)."
        },
        {
            "flag": "",
            "long": "--ignore-case",
            "arg": null,
            "description": "Sorting and filtering refs are case insensitive."
        }
    ],
    "examples": [
        "An example directly producing formatted text. Show the most recent 3 tagged commits:",
        "#!/bin/sh",
        "git for-each-ref --count=3 --sort='-*authordate' \\",
        "--format='From: %(*authorname) %(*authoremail)",
        "Subject: %(*subject)",
        "Date: %(*authordate)",
        "Ref: %(*refname)",
        "%(*body)",
        "' 'refs/tags'",
        "A simple example showing the use of shell eval on the output, demonstrating the use of",
        "--shell. List the prefixes of all heads:",
        "#!/bin/sh",
        "git for-each-ref --shell --format=\"ref=%(refname)\" refs/heads | \\",
        "while read entry",
        "do",
        "eval \"$entry\"",
        "echo `dirname $ref`",
        "done",
        "A bit more elaborate report on tags, demonstrating that the format may be an entire script:",
        "#!/bin/sh",
        "fmt='",
        "r=%(refname)",
        "t=%(*objecttype)",
        "T=${r#refs/tags/}",
        "o=%(*objectname)",
        "n=%(*authorname)",
        "e=%(*authoremail)",
        "s=%(*subject)",
        "d=%(*authordate)",
        "b=%(*body)",
        "kind=Tag",
        "if test \"z$t\" = z",
        "then",
        "# could be a lightweight tag",
        "t=%(objecttype)",
        "kind=\"Lightweight tag\"",
        "o=%(objectname)",
        "n=%(authorname)",
        "e=%(authoremail)",
        "s=%(subject)",
        "d=%(authordate)",
        "b=%(body)",
        "fi",
        "echo \"$kind $T points at a $t object $o\"",
        "if test \"z$t\" = zcommit",
        "then",
        "echo \"The commit was authored by $n $e",
        "at $d, and titled",
        "$s",
        "Its message reads as:",
        "echo \"$b\" | sed -e \"s/^/    /\"",
        "echo",
        "fi",
        "eval=`git for-each-ref --shell --format=\"$fmt\" \\",
        "--sort='*objecttype' \\",
        "--sort=-taggerdate \\",
        "refs/tags`",
        "eval \"$eval\"",
        "An example to show the usage of %(if)...%(then)...%(else)...%(end). This prefixes the current",
        "branch with a star.",
        "git for-each-ref --format=\"%(if)%(HEAD)%(then)* %(else)  %(end)%(refname:short)\" refs/heads/",
        "An example to show the usage of %(if)...%(then)...%(end). This prints the authorname, if",
        "present.",
        "git for-each-ref --format=\"%(refname)%(if)%(authorname)%(then) Authored by: %(authorname)%(end)\""
    ],
    "see_also": [
        {
            "name": "git-show-ref",
            "section": "1",
            "url": "https://www.chedong.com/phpMan.php/man/git-show-ref/1/json"
        }
    ],
    "tldr": {
        "source": "official",
        "description": "List and optionally format references (branches, tags) in a Git repository.",
        "examples": [
            {
                "description": "List all refs (branches and tags)",
                "command": "git for-each-ref"
            },
            {
                "description": "List only branches",
                "command": "git for-each-ref refs/heads/"
            },
            {
                "description": "List only tags",
                "command": "git for-each-ref refs/tags/"
            },
            {
                "description": "Show branches merged into `HEAD`",
                "command": "git for-each-ref --merged HEAD refs/heads/"
            },
            {
                "description": "List short names of all refs",
                "command": "git for-each-ref --format \"%(refname:short)\""
            },
            {
                "description": "Sort refs by committer date (most recent first)",
                "command": "git for-each-ref --sort -committerdate"
            },
            {
                "description": "Sort refs by committer date (oldest first)",
                "command": "git for-each-ref --sort committerdate"
            },
            {
                "description": "Limit output to a specified number of refs",
                "command": "git for-each-ref --count {{count}}"
            }
        ]
    }
}