git aliases operate in the wrong directory

后端 未结 2 1831
清歌不尽
清歌不尽 2020-12-15 06:22

Summary: the current working directory of commands run through git aliases is wrong.

The easiest way to demonstrate this is to have a git alias like so:



        
2条回答
  •  攒了一身酷
    2020-12-15 06:57

    TL;DR: add cd -- ${GIT_PREFIX:-.}; in front of the rest of the alias, e.g.:

    [alias]
        pwd = !cd -- ${GIT_PREFIX:-.}; pwd
    

    This is a (mis?)feature, but you can work around it with $GIT_PREFIX as noted in this other stackoverflow question and answer:

    #! /bin/sh
    # script to do stuff in a git dir
    # since we're sometimes run from a git alias we need
    # to cd back into $GIT_PREFIX if it's set
    [ "$GIT_PREFIX" != "" ] && cd -- "$GIT_PREFIX"
    ... rest of script ...
    

    (As Tom Hale noted in a comment, one can shorten this using the sh / bash / POSIX-shell feature ${var:-default}, where an unset or empty-string variable value expands to the default given after the colon-dash character pair. We use the -- because bash has added options to the cd command, so for robustness we should handle a case where the prefix variable contains, say, -e. The double quotes are not necessary either: I used them above for symmetry with the test command, which the longer version above spells as [.)

提交回复
热议问题