脚本/ Bash:如何添加if语句并检查致命错误?

时间:2015-12-08 16:14:39

标签: git bash

我刚刚编写了一个小脚本,它从GIT存储库中提取,然后运行两个命令。

我喜欢在输入错误的密码时添加一个if语句,以至于我没有运行其他两个命令

 
  #!/bin/sh
echo Pulling GIT repository and do command1 and command2. Press Enter to start...
read
cd /myProjects
git pull 
printf  "\n \n command1 will start now  \n \n"
command1
printf  "\n \n command2 will start now \n\n"
command2
echo Finished. Press Enter to exit ...
read

我想以下情况会很好。我只是无法找出if条件中的内容。

 #!/bin/sh
    echo Pulling GIT repository and do command1 and command2. Press Enter to start...
    read
    cd /myProjects
    git pull 
if [ the Password was wrong ] ; then
   printf  "\n \n command1 will start now  \n \n"
    command1
    printf  "\n \n command2 will start now \n\n"
    command2
    echo Finished. Press Enter to exit ...
    read
else
  echo Your password was wrong
fi

请注意错误密码的输出是:

fatal: remote error: Invalid username or password.

2 个答案:

答案 0 :(得分:0)

@tripleee有正确的答案。另一种写作方式是:

if git pull; then
    command1
    command2
fi

据推测,git pull的错误输出将非常清晰,您不需要添加错误消息。

答案 1 :(得分:0)

在bash中写这个的更好的方法如下。

git pull && command1 && command2

这将导致以下行为。如果git pull secceeds它执行command1,如果command1成功,它将执行command2。

如果你想要执行command2,无论command1是否失败,你都可以按如下方式编写它。

git pull && command1 || command2

这将导致只有在git pull成功时才执行command1和2。

更高级的东西的其他选项是使用$?变量,它给出了最后执行的命令的数字退出代码。在bash中通常0如果命令成功或者来自1或更高的任何数字以指示特定的失败案例。

这可以让你做更多高级的东西,比如

if [ $? -gt 0 && $? -lt 5 ] ; then
    command1
elif [ $? -eq 6 ] ; then
    stuff
else
    things
fi