여러 유형의 VCS에서 작업하려는 bash 스크립트를 작성 중입니다. 일반적인 info 명령을 실행하고 리턴 코드, 성공 또는 오류를 확인하여 디렉토리가 시스템의 저장소인지 테스트하려고합니다. 의사 코드에서 :
if a svn command succeded;
Then run svn commands
elif a darcs command succeded;
Then run darcs commands
elif a mercurial command succeded;
then run hg commands
else
something else
fi
예를 들어 명령을 실행
하고 반환 코드를 얻는 데 darcs show repo
사용할 $?
수 있습니다.
내 질문은 : 한 줄에 반환 코드 번호를 실행하고 반환하는 깔끔한 방법이 있습니까? 예를 들어
if [ 0 -eq `darcs show repo`$? ];
아니면 함수를 정의해야합니까?
또한 stderr과 stdout을 모두 인쇄해야합니다.
답변
리턴 코드를 자동으로 확인하는 경우 :
if (darcs show repo); then
echo "repo exists"
else
echo "repo does not exist"
fi
명령을 실행하고 && (논리 AND) 또는 ||를 사용할 수도 있습니다. (논리적 OR) 이후에 성공했는지 여부를 확인하십시오.
darcs show repo && echo "repo exists"
darcs show repo || echo "repo does not exist"
리디렉션 stdout
과 stderr
함께 한 번 할 수 있습니다exec
exec 6>&1
exec 7>&2
exec >/dev/null 2>&1
if (darcs show repo); then
repo="darcs"
elif (test -d .git); then
repo="git"
fi
# The user won't see this
echo "You can't see my $repo"
exec 1>&6 6>&-
exec 2>&7 7>&-
# The user will see this
echo "You have $repo installed"
첫 번째 두 사람은 exec
구원되어 stdin
및 stderr
파일 기술자에 두 번째 리디렉션 /dev/null
(원한다면 또는 다른 곳을). 마지막 두 개 exec
는 파일 디스크립터를 다시 복원합니다. 그 사이의 모든 것은 아무데도 리디렉션되지 않습니다.
Gilles가 제안한 다른 리포 검사를 추가하십시오.
답변
다른 사람들이 이미 언급했듯이 성공 if command
여부를 테스트합니다 command
. 실제로 [ … ]
는 일반적인 명령이며, 드물기는하지만 조건 외부 if
또는 while
조건 밖에서 사용할 수 있습니다 .
그러나이 응용 프로그램의 경우 특성 디렉토리가 있는지 테스트합니다. 더 많은 경우에 맞습니다. 배쉬 / ksh / zsh / 대시 버전 (예상치 않음) :
vc=
if [ -d .svn ]; then
vc=svn
elif [ -d CVS ]; then
vc=cvs
else
d=$(pwd -P)
while [ -n "$d" ]; do
if [ -d "$d/.bzr" ]; then
vc=bzr
elif [ -d "$d/_darcs" ]; then
vc=darcs
elif [ -d "$d/.git" ]; then
vc=git
elif [ -d "$d/.hg" ]; then
vc=hg
fi
if [ -n "$vc" ]; then break; fi
d=${d%/*}
done
fi
if [ -z "$vc" ]; then
echo 1>&2 "This directory does not seem to be under version control."
exit 2
fi
답변
글쎄, 그것은 꽤 예쁘지는 않지만 인라인을 수행하는 한 가지 방법입니다.
if darcs show repo > /dev/null 2>&1; then <do something>; fi
정의에 따라 명령의 종료 코드를 테스트하면 성공 또는 실패 이상을 원하지 않는 한 명시 적으로 비교할 필요가 없습니다. 더 우아한 방법이있을 것입니다.
답변
간결한 또 다른 옵션은 다음과 같습니다.
[ -d .svn ] && { svn command 1; svn command 2; }