Bash 脚本通过测试命令返回状态来检测版本控制系统

Nia*_*phy 11 bash shell-script exit-status

我正在编写一个 bash 脚本,我想为多种类型的 VCS 工作。我正在考虑通过运行典型的 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
Run Code Online (Sandbox Code Playgroud)

我可以运行一个命令,例如 darcs show repo并使用它$?来获取它的返回码。

我的问题是:有没有一种简洁的方法可以在一行中运行并返回返回代码号?例如

if [ 0 -eq `darcs show repo`$? ]; 
Run Code Online (Sandbox Code Playgroud)

还是我必须定义一个函数?

一个额外的要求是 stderr 和 stdout 都应该被打印出来。

wag*_*wag 15

如果自动检查返回码:

if (darcs show repo); then
  echo "repo exists"
else
  echo "repo does not exist"
fi
Run Code Online (Sandbox Code Playgroud)

您还可以运行命令并使用 &&(逻辑与)或 || (逻辑或)之后检查它是否成功:

darcs show repo && echo "repo exists"
darcs show repo || echo "repo does not exist"
Run Code Online (Sandbox Code Playgroud)

重定向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"
Run Code Online (Sandbox Code Playgroud)

前两个exec是保存stdinstderr文件描述符,第三重定向到两个/dev/null(或者其他地方,如果愿意)。最后两个exec再次恢复文件描述符。两者之间的所有内容都被重定向到无处。

像 Gilles 建议的那样附加其他回购检查。

  • 为什么要在子shell中运行这些?这是不必要的。 (2认同)