在bash中退出脚本功能

时间:2018-05-14 12:50:40

标签: bash shell unix

我有以下脚本,我将通过jenkins运行:

  [TestMethod]
        public void AuthoriseDeviceProfileTest()
        {
            long paramUserID=1, string paramClientMakeModel=test";
            IDeviceAuthorisationService DeviceAuthorisationService= new DeviceAuthorisationService();

            try
            {

                DeviceAuthorisationService.AuthoriseDeviceProfile(paramUserID, paramClientMakeModel);
                Assert.IsNull(paramUserID);

            }
            catch (Exception e)
            {
                Assert.AreNotEqual("Exception of type was thrown", e.Message);
            }
        }
    }

正如你所看到的那样,下面的代码有很多重复,这有助于我通过抛出错误代码1来使jenkins工作失败:

#!/bin/bash

function getToken
{ 
    echo "function to get token"
}

function call_init
{
    echo "Creating a config file"

}

function call_list
{
    echo "calling list*"
}

#Starting execution
if [[ -z "$TOKEN" ]]; then
    TOKEN=$(getToken)
    if [ $? -ne 0 ]; then
    exit 1
    fi
fi

echo "Creating a config file and populating it"
call_init
if [ $? -ne 0 ]; then
exit 1
fi


if [ -n $ACTION ]; then
case "$ACTION" in

'list')  echo "Action is list"
     call_list
     if [ $? -ne 0 ]; then
     exit 1
     fi   
;;
'update')  echo  "Section is update"
;;
'delete')  echo  "Section is delete"
;;
*) echo "This is a default message"
   ;;
esac
fi

处理此问题的最有效方法是什么?我需要它始终用1退出代码。

P.S:我经历了Checking Bash exit status of several commands efficiently,但无法让它适用于上述脚本。

1 个答案:

答案 0 :(得分:3)

最好的方法是使用显式错误检查。

您目前的模式可以简化,以下都是等效的:

run_command
if [ $? -ne 0 ]; then
    print_error
    exit 1
fi
if ! run_command; then
    print_error
    exit 1
fi
run_command || { print_error; exit 1; }

或者是最简单的形式,没有错误信息:

run_command || exit 1

作为替代方案,您可能希望使用set -e。 您可能也对set -o pipefail感兴趣。

这些不是首选的解决方案,正如@William指出的那样,但对于让简单的脚本抛出错误非常有用:

  

请注意,set -e通常不被视为最佳做法。在边缘情况下,它的语义非常出乎意料(例如,如果在函数中调用set -e),更重要的是,使用不同版本的shell会发生显着变化。通过运行cmd || exit

显式调用exit更好

如果命令返回非零,您可以使用set -e使bash挽救,并set +e禁用此行为。

set: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
    Set or unset values of shell options and positional parameters.

    Change the value of shell attributes and positional parameters, or
    display the names and values of shell variables.

    Options:
      [...]
      -e  Exit immediately if a command exits with a non-zero status.
      [...]
      -o option-name
          Set the variable corresponding to option-name:
              [...]
              pipefail     the return value of a pipeline is the status of
                           the last command to exit with a non-zero status,
                           or zero if no command exited with a non-zero status
              [...]

要使用此功能,必须在需要之前启用该选项。

例如:

# disable 'exit immediately' (the default)
set +e

echo "running false..."
false
echo "we're still running"

# enable 'exit immediately'
set -e

echo "running false..."
false
echo "this should never get printed"

set -o pipefail必须与set -e

一起使用
# enable 'exit immediately'
set -e

# disable 'pipefail' (the default)
set +o pipefail

echo "running false | true..."
false | true
echo "we're still running (only the last exit status is considered)"

# enable 'pipefail'
set -o pipefail

echo "running false | true..."
false | true
echo "this should never get printed"