如何返回退出代码?错误:返回:阅读:需要数字参数

Mou*_*inX 7 bash shell-script function

这是我的脚本的简化版本。我的问题是,apt-get在这种情况下如何返回退出代码?

#!/bin/bash
install_auto() {
apt-get -h > /dev/null 2>&1
if [ $? -eq 0 ] ; then
    return $(sudo apt-get install --assume-yes $@)
fi
return 1
}
echo "installing $@"
install_auto "$@"
echo $?
echo "finished"
exit 0
Run Code Online (Sandbox Code Playgroud)

输出是:

./install_test.sh: line 5: return: Reading: numeric argument required
Run Code Online (Sandbox Code Playgroud)

更新:我想出了一些有效的方法:

return $(sudo apt-get install --assume-yes "$@" >/dev/null 2>&1; echo $?)
Run Code Online (Sandbox Code Playgroud)

这是一个好方法吗?

ter*_*don 7

Bashreturn()只能返回数字参数。在任何情况下,默认情况下,它将返回上次命令运行的退出状态。所以,你真正需要的是:

#!/usr/bin/env bash
install_auto() {
apt-get -h > /dev/null 2>&1
if [ $? -eq 0 ] ; then
    sudo apt-get install --assume-yes $@
fi
}
Run Code Online (Sandbox Code Playgroud)

您不需要显式设置要返回的值,因为默认情况下函数将返回$?. 但是,如果第一个apt命令失败并且您没有进入if循环,那将不起作用。要使其更健壮,请使用以下命令:

#!/usr/bin/env bash
install_auto() {
apt-get -h > /dev/null 2>&1
ret=$?
if [ $ret -eq 0 ] ; then
    ## If this is executed, the else is ignored and $? will be
    ## returned. Here, $?will be the exit status of this command
    sudo apt-get install --assume-yes $@
else
    ## Else, return the exit value of the first apt-get
    return $ret
fi
}
Run Code Online (Sandbox Code Playgroud)

一般规则是,为了让函数返回特定作业的退出状态,而不一定是它运行的最后一个,您需要将退出状态保存到变量并返回变量:

function foo() {
    run_a_command arg1 arg2 argN
    ## Save the command's exit status into a variable
    return_value= $?

    [the rest of the function  goes here]
    ## return the variable
    return $return_value
}
Run Code Online (Sandbox Code Playgroud)

编辑:实际上,正如@gniourf_gniourf 在评论中指出的那样,您可以使用&&以下方法极大地简化整个过程:

install_auto() {
  apt-get -h > /dev/null 2>&1 &&
  sudo apt-get install --assume-yes $@
}
Run Code Online (Sandbox Code Playgroud)

此函数的返回值将是以下之一:

  1. 如果apt-get -h 失败,它将返回其退出代码
  2. 如果apt-get -h成功,它将返回 的退出代码sudo apt-get install

  • `ret` 变量没用。`apt-get -h > /dev/null 2>&1 && sudo apt-get install --assume-yes "$@"` 会做同样的事情。哦,使用更多的引号,特别是对于 `$@` (2认同)