終了コードを返す方法は?エラー:戻り:読み取り:数値引数が必要です。

終了コードを返す方法は?エラー:戻り:読み取り:数値引数が必要です。

これは私のスクリプトの単純化されたバージョンです。私の質問は、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

出力は次のとおりです

./install_test.sh: line 5: return: Reading: numeric argument required

アップデート:うまくいくことを見つけました。

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

これは良いアプローチですか?

ベストアンサー1

Bashはreturn()数値パラメータのみを返すことができます。とにかく、デフォルトでは最後のコマンド実行の終了ステータスを返します。したがって、実際に必要なものは次のとおりです。

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

関数はデフォルトで返されるので、返す値を明示的に設定する必要はありません$?。ただし、最初のコマンドが失敗し、ループを入力しないと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
}

一般的なルールは、関数が最後に実行したジョブではなく、特定のジョブの終了ステータスを返すには、終了ステータスを変数に保存し、その変数を返す必要があることです。

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
}

編集:実際には、@gniourf_gniourfがコメントで指摘したように、以下を使用してすべてを大幅に簡素化できます&&

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

この関数の戻り値は次のいずれかです。

  1. 失敗した場合はapt-get -h 終了コードを返します。
  2. 成功するとapt-get -h終了コードが返されますsudo apt-get install

おすすめ記事