현재 디렉토리가 Git 저장소인지 확인
zsh에서 Git 관리를위한 일련의 스크립트를 작성하고 있습니다.현재 디렉토리가 Git 저장소인지 어떻게 확인합니까? (Git 리포지토리에 있지 않을 때는 많은 명령을 실행하고 많은
fatal: Not a git repository
응답을 얻고 싶지 않습니다 ).
bash 완성 파일에서 복사 한 다음은 순진한 방법입니다.
# Copyright (C) 2006,2007 Shawn O. Pearce <spearce@spearce.org>
# Conceptually based on gitcompletion (http://gitweb.hawaga.org.uk/).
# Distributed under the GNU General Public License, version 2.0.
if [ -d .git ]; then
echo .git;
else
git rev-parse --git-dir 2> /dev/null;
fi;
함수로 감싸거나 스크립트에서 사용할 수 있습니다.bash 또는 zsh에 적합한 한 줄 조건으로 응축
[ -d .git ] || git rev-parse --git-dir > /dev/null 2>&1
당신이 사용할 수있는:
git rev-parse --is-inside-work-tree
git repos 작업 트리에 있으면 'true'로 인쇄됩니다.자식 저장소 외부에 있고 'false'를 인쇄하지 않으면 여전히 STDERR로 출력을 반환합니다.이 답변에서 가져온 것 : https :
git rev-parse --git-dir 사용
만약 git rev-parse --git-dir> / dev / null 2> & 1; 그때
: # 이것은 유효한 자식 저장소입니다.
# 디렉토리가 최상위 레벨이 아닐 수 있습니다.
# 관심이 있다면 git rev-parse 명령의 출력을 확인하십시오)
그밖에
: # 이것은 git 저장소가 아닙니다.
fi
또는 당신은 이것을 할 수 있습니다 :
inside_git_repo="$(git rev-parse --is-inside-work-tree 2>/dev/null)"
if [ "$inside_git_repo" ]; then
echo "inside git repo"
else
echo "not in git repo"
fi
공개적으로 액세스 가능하거나 문서화 된 방법이 있는지 확실하지 않습니다 (git 소스 자체에서 사용 / 남용 할 수있는 내부 git 함수가 있습니다)당신은 같은 것을 할 수 있습니다;
if ! git ls-files >& /dev/null; then
echo "not in git"
fi
다른 해결책은 명령의 종료 코드를 확인하는 것입니다.
git rev-parse 2> /dev/null; [ $? == 0 ] && echo 1
git repository 폴더에 있으면 1이 인쇄됩니다.
바탕으로 :
[ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" == "true" ]
중복 작업을 포함하지 않으며
-e
모드 에서 작동 합니다.
- @ go2null이 지적했듯이 이것은 베어 리포지토리 에서 작동하지 않습니다. 어떤 이유로 든 베어 리포지토리로 작업하려는 경우
git rev-parse
출력을 무시하고 성공 여부 만 확인할 수 있습니다 .- 위의 줄은 스크립팅을 위해 압축되어 있으며 사실상 모든
git
명령은 작업 트리 내에서만 유효 하기 때문에이 단점을 고려하지 않습니다 . 따라서 스크립팅 목적으로 "git repo"내부가 아닌 작업 트리 내부에 관심이있을 것입니다.
- 위의 줄은 스크립팅을 위해 압축되어 있으며 사실상 모든
이것은 나를 위해 작동합니다. 여전히 오류가 발생하지만 쉽게 억제 할 수 있습니다. 하위 폴더 내에서도 작동합니다!
자식 상태> / dev / null 2> & 1
&& echo Hello World!조건부로 더 많은 작업을 수행해야하는 경우이를 if then 문에 넣을 수 있습니다.
You can add to or replace your $PS1 in your zshrc with one or another git-prompt tools. This way you can be conveniently apprised of whether you're in a git repo and the state of the repo is in.
This answer provides a sample POSIX shell function and a usage example to complement @jabbie's answer.
is_inside_git_repo() {
git rev-parse --is-inside-work-tree >/dev/null 2>&1
}
git
returns errorlevel 0
if it is inside a git repository, else it returns errorlevel 128
. (It also returns true
or false
if it is inside a git repository.)
Usage example
for repo in *; do
# skip files
[ -d "$repo" ] || continue
# run commands in subshell so each loop starts in the current dir
(
cd "$repo"
# skip plain directories
is_inside_git_repo || continue
printf '== %s ==\n' "$repo"
git remote update --prune 'origin' # example command
# other commands here
)
done
# check if git repo
if [ $(git rev-parse --is-inside-work-tree) = true ]; then
echo "yes, is a git repo"
git pull
else
echo "no, is not a git repo"
git clone url --depth 1
fi
Why not using exit codes? If a git repository exists in the current directory, then git branch
and git tag
commands return exit code of 0; otherwise, a non-zero exit code will be returned. This way, you can determine if a git repository exist or not. Simply, you can run:
git tag > /dev/null 2>&1 && [ $? -eq 0 ]
Advantage: Flexibe. It works for both bare and non-bare repositories, and in sh, zsh and bash.
Explanation
git tag
: Getting tags of the repository to determine if exists or not.> /dev/null 2>&1
: Preventing from printing anything, including normal and error outputs.[ $? -eq 0 ]
: Check if the previous command returned with exit code 0 or not. As you may know, every non-zero exit means something bad happened.$?
gets the exit code of the previous command, and[
,-eq
and]
perform the comparison.
As an example, you can create a file named check-git-repo
with the following contents, make it executable and run it:
#!/bin/sh
if git tag > /dev/null 2>&1 && [ $? -eq 0 ]; then
echo "Repository exists!";
else
echo "No repository here.";
fi
! git rev-parse --is-inside-work-tree >/dev/null 2>&1 || {
printf '%s\n\n' "GIT repository detected." && git status
}
The ! negates so even if you run this in a directory that is not a git repo it will not give you some fatal errors
The >/dev/null 2>&1 sends the messages to /dev/null since you're just after the exit status. The {} are for command groupings so all commands after the || will run if the git rev-parse succeeded since we use a ! which negated the exit status of git rev-parse. The printf is just to print some message and git status to print the status of the repo.
Wrap it in a function or put it in a script. Hope this helps
참고URL : https://stackoverflow.com/questions/2180270/check-if-current-directory-is-a-git-repository
'programing' 카테고리의 다른 글
두 개의 Java 8 스트림 또는 추가 요소를 스트림에 추가 (0) | 2020.06.02 |
---|---|
장치 픽셀 비율은 정확히 무엇입니까? (0) | 2020.06.02 |
python pandas의 열 이름에서 열 인덱스 가져 오기 (0) | 2020.06.02 |
mongo 쉘의 모든 데이터베이스를 나열하는 방법은 무엇입니까? (0) | 2020.06.02 |
탈옥 된 전화기에서 iOS 앱이 실행되고 있는지 어떻게 알 수 있습니까? (0) | 2020.06.02 |