Bash script to detect the version control system by testing command return status

bashexit-statusshell-script

I am working on a bash script that I would like to work for several types of VCS.
I am thinking of testing if a directory is a repo for a system by running a typical info command and checking the return code, success or error.
In pseudo code:

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

I can run a command, e.g.
darcs show repo and use $? to get its return code.

My question is: is there a neat way to run and return the return code number in one line? for example

if [ 0 -eq `darcs show repo`$? ]; 

Or do I have to define a function?

An added requirement is that both stderr and stdout should be printed.

Best Answer

If automatically checks the return code:

if (darcs show repo); then
  echo "repo exists"
else
  echo "repo does not exist"
fi

You could also run the command and use && (logical AND) or || (logical OR) afterwards to check if it succeeded or not:

darcs show repo && echo "repo exists"
darcs show repo || echo "repo does not exist"

Redirecting stdout and stderr can be done once with 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"

The first two exec are saving the stdin and stderr file descriptors, the third redirects both to /dev/null (or somewhere other if wished). The last two exec restore the file descriptors again. Everything in between gets redirected to nowhere.

Append other repo checks like Gilles suggested.

Related Question