
これは私のスクリプトの単純化されたバージョンです。私の質問は、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 $@
}
この関数の戻り値は次のいずれかです。
- 失敗した場合は
apt-get -h
終了コードを返します。 - 成功すると
apt-get -h
終了コードが返されますsudo apt-get install
。
答え2
完全性のために@terdonと@gniourf_gniourfが提案したように、いくつかの修正を適用した実際の機能は次のとおりです。
install_auto() {
if [ ! $# -gt 0 ] ; then
echo "usage: $0 package_name [package_name ...]"
fi
apt-get -h > /dev/null 2>&1
if [ $? -eq 0 ] ; then
if [ -f "$@" ] || [[ "$@" =~ '/' ]] ; then
sudo gdebi -n "$@"
return $?
else
sudo apt-get install --assume-yes "$@"
return $?
fi
fi
zypper help > /dev/null 2>&1
if [ $? -eq 0 ] ; then
sudo zypper --non-interactive --no-gpg-checks --quiet install --auto-agree-with-licenses "$@"
return $?
fi
#may check other package managers in the future
echo "ERROR: package manager not found"
return 255
}
追加のアドバイスをいただきありがとうございます。