Capture output from git command?

核能气质少年 提交于 2019-12-03 13:26:34

git clone does provide a exit code you can read with $? like follows:

git clone user@server:repo
echo $?

This will print 0 if everything worked just fine. If for example the folder is not a git repository you will get the exit code 128.

you can check if the clone worked as follows:

git clone user@server:repo localrepo --quiet
success=$?
if [[ $success -eq 0 ]];
then
    echo "Repository successfully cloned."
else
    echo "Something went wrong!"
fi

--quietwill suppress any output from git, as long as there are no errors. So if you just remove the else-branch you will get you positive output or the error produced by git.

git clone user@server:repo localrepo > git.log 2>&1
if [[ $? eq 0 ]];
then
   echo Repository successfully cloned.
else
   cat git.log
   echo Repository cloning failed.
fi

rm git.log

Explanation:

git clone user@server:repo localrepo > git.log 2>&1 Redirects stdout and stderr streams to git.log. > git.log redirects stdout to git.log 2>&1 redirects stderr to the same place as stdout(thus, git.log).

$? eq 0 Checks the retcode of git which should be 0 if the clone was successful.

cat git.log outputs the contents of the git.log file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!