シェルスクリプトのデザインパターンまたはベストプラクティス [closed] 質問する

シェルスクリプトのデザインパターンまたはベストプラクティス [closed] 質問する

シェル スクリプト (sh、bash など) のベスト プラクティスや設計パターンについて説明しているリソースをご存知の方はいらっしゃいますか?

ベストアンサー1

私はかなり複雑なシェル スクリプトを書いたことがありますが、私の最初の提案は「やらない」ことです。その理由は、スクリプトを妨害したり、危険にさらしたりする小さな間違いを犯す可能性が非常に高いからです。

とはいえ、私の個人的な経験以外にあなたに伝えるリソースはありません。これは私が通常行っていることです。やりすぎではありますが、堅実な傾向があります。とても冗長。

呼び出し

スクリプトが長いオプションと短いオプションを受け入れるようにします。オプションを解析するコマンドは getopt と getopts の 2 つがあるので注意してください。トラブルが少ないので、getopt を使用してください。

CommandLineOptions__config_file=""
CommandLineOptions__debug_level=""

getopt_results=`getopt -s bash -o c:d:: --long config_file:,debug_level:: -- "$@"`

if test $? != 0
then
    echo "unrecognized option"
    exit 1
fi

eval set -- "$getopt_results"

while true
do
    case "$1" in
        --config_file)
            CommandLineOptions__config_file="$2";
            shift 2;
            ;;
        --debug_level)
            CommandLineOptions__debug_level="$2";
            shift 2;
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "$0: unparseable option $1"
            EXCEPTION=$Main__ParameterException
            EXCEPTION_MSG="unparseable option $1"
            exit 1
            ;;
    esac
done

if test "x$CommandLineOptions__config_file" == "x"
then
    echo "$0: missing config_file parameter"
    EXCEPTION=$Main__ParameterException
    EXCEPTION_MSG="missing config_file parameter"
    exit 1
fi

もう 1 つの重要な点は、プログラムが正常に完了した場合は必ず 0 を返し、何か問題が発生した場合は 0 以外の値を返す必要があるということです。

関数呼び出し

bash で関数を呼び出すことができますが、呼び出し前に関数を定義することを忘れないでください。関数はスクリプトのようなもので、数値のみを返すことができます。つまり、文字列値を返すには別の戦略を考案する必要があります。私の戦略は、RESULT という変数を使用して結果を保存し、関数が正常に完了した場合は 0 を返すことです。また、ゼロ以外の値を返す場合は例外を発生させ、2 つの「例外変数」(私の場合は EXCEPTION と EXCEPTION_MSG) を設定することができます。1 つ目は例外タイプを含み、2 つ目は人間が読めるメッセージです。

関数を呼び出すと、関数のパラメータが特別な変数 $0、$1 などに割り当てられます。より意味のある名前を付けることをお勧めします。関数内の変数をローカルとして宣言します。

function foo {
   local bar="$0"
}

エラーが発生しやすい状況

bashでは、特に宣言しない限り、未設定の変数は空の文字列として使用されます。これはタイプミスの場合に非常に危険です。間違った型付けの変数は報告されず、空として評価されます。

set -o nounset

これを防ぐには、次の操作を実行します。ただし、これを行うと、未定義の変数を評価するたびにプログラムが中止されるため、注意してください。このため、変数が定義されていないかどうかを確認する唯一の方法は次のとおりです。

if test "x${foo:-notset}" == "xnotset"
then
    echo "foo not set"
fi

変数を読み取り専用として宣言できます。

readonly readonly_var="foo"

モジュール化

次のコードを使用すると、「Python のような」モジュール化を実現できます。

set -o nounset
function getScriptAbsoluteDir {
    # @description used to get the script path
    # @param $1 the script $0 parameter
    local script_invoke_path="$1"
    local cwd=`pwd`

    # absolute path ? if so, the first character is a /
    if test "x${script_invoke_path:0:1}" = 'x/'
    then
        RESULT=`dirname "$script_invoke_path"`
    else
        RESULT=`dirname "$cwd/$script_invoke_path"`
    fi
}

script_invoke_path="$0"
script_name=`basename "$0"`
getScriptAbsoluteDir "$script_invoke_path"
script_absolute_dir=$RESULT

function import() { 
    # @description importer routine to get external functionality.
    # @description the first location searched is the script directory.
    # @description if not found, search the module in the paths contained in $SHELL_LIBRARY_PATH environment variable
    # @param $1 the .shinc file to import, without .shinc extension
    module=$1

    if test "x$module" == "x"
    then
        echo "$script_name : Unable to import unspecified module. Dying."
        exit 1
    fi

    if test "x${script_absolute_dir:-notset}" == "xnotset"
    then
        echo "$script_name : Undefined script absolute dir. Did you remove getScriptAbsoluteDir? Dying."
        exit 1
    fi

    if test "x$script_absolute_dir" == "x"
    then
        echo "$script_name : empty script path. Dying."
        exit 1
    fi

    if test -e "$script_absolute_dir/$module.shinc"
    then
        # import from script directory
        . "$script_absolute_dir/$module.shinc"
    elif test "x${SHELL_LIBRARY_PATH:-notset}" != "xnotset"
    then
        # import from the shell script library path
        # save the separator and use the ':' instead
        local saved_IFS="$IFS"
        IFS=':'
        for path in $SHELL_LIBRARY_PATH
        do
            if test -e "$path/$module.shinc"
            then
                . "$path/$module.shinc"
                return
            fi
        done
        # restore the standard separator
        IFS="$saved_IFS"
    fi
    echo "$script_name : Unable to find module $module."
    exit 1
} 

拡張子が.shincのファイルを次の構文でインポートできます。

「AModule/ModuleFile」をインポートします

これは SHELL_LIBRARY_PATH で検索されます。常にグローバル名前空間でインポートするため、すべての関数と変数に適切なプレフィックスを付けることを忘れないでください。そうしないと、名前が衝突する危険があります。私は Python ドットとして二重アンダースコアを使用しています。

また、これをモジュールの最初に入れてください

# avoid double inclusion
if test "${BashInclude__imported+defined}" == "defined"
then
    return 0
fi
BashInclude__imported=1

オブジェクト指向プログラミング

bash では、オブジェクトの割り当ての非常に複雑なシステムを構築しない限り、オブジェクト指向プログラミングを行うことはできません (それについては考えました。実現可能ですが、非常識です)。ただし、実際には、「シングルトン指向プログラミング」を行うことができます。つまり、各オブジェクトのインスタンスは 1 つだけになります。

私がやっていることは、オブジェクトをモジュールに定義することです(モジュール化のエントリを参照)。次に、空の変数(メンバー変数に類似)、init関数(コンストラクタ)、およびメンバー関数を定義します。次のサンプルコードを参照してください。

# avoid double inclusion
if test "${Table__imported+defined}" == "defined"
then
    return 0
fi
Table__imported=1

readonly Table__NoException=""
readonly Table__ParameterException="Table__ParameterException"
readonly Table__MySqlException="Table__MySqlException"
readonly Table__NotInitializedException="Table__NotInitializedException"
readonly Table__AlreadyInitializedException="Table__AlreadyInitializedException"

# an example for module enum constants, used in the mysql table, in this case
readonly Table__GENDER_MALE="GENDER_MALE"
readonly Table__GENDER_FEMALE="GENDER_FEMALE"

# private: prefixed with p_ (a bash variable cannot start with _)
p_Table__mysql_exec="" # will contain the executed mysql command 

p_Table__initialized=0

function Table__init {
    # @description init the module with the database parameters
    # @param $1 the mysql config file
    # @exception Table__NoException, Table__ParameterException

    EXCEPTION=""
    EXCEPTION_MSG=""
    EXCEPTION_FUNC=""
    RESULT=""

    if test $p_Table__initialized -ne 0
    then
        EXCEPTION=$Table__AlreadyInitializedException   
        EXCEPTION_MSG="module already initialized"
        EXCEPTION_FUNC="$FUNCNAME"
        return 1
    fi


    local config_file="$1"

      # yes, I am aware that I could put default parameters and other niceties, but I am lazy today
      if test "x$config_file" = "x"; then
          EXCEPTION=$Table__ParameterException
          EXCEPTION_MSG="missing parameter config file"
          EXCEPTION_FUNC="$FUNCNAME"
          return 1
      fi


    p_Table__mysql_exec="mysql --defaults-file=$config_file --silent --skip-column-names -e "

    # mark the module as initialized
    p_Table__initialized=1

    EXCEPTION=$Table__NoException
    EXCEPTION_MSG=""
    EXCEPTION_FUNC=""
    return 0

}

function Table__getName() {
    # @description gets the name of the person 
    # @param $1 the row identifier
    # @result the name
    
    EXCEPTION=""
    EXCEPTION_MSG=""
    EXCEPTION_FUNC=""
    RESULT=""
    
    if test $p_Table__initialized -eq 0
    then
        EXCEPTION=$Table__NotInitializedException
        EXCEPTION_MSG="module not initialized"
        EXCEPTION_FUNC="$FUNCNAME"
        return 1
    fi
    
    id=$1
      
      if test "x$id" = "x"; then
          EXCEPTION=$Table__ParameterException
          EXCEPTION_MSG="missing parameter identifier"
          EXCEPTION_FUNC="$FUNCNAME"
          return 1
      fi
    
    local name=`$p_Table__mysql_exec "SELECT name FROM table WHERE id = '$id'"`
      if test $? != 0 ; then
        EXCEPTION=$Table__MySqlException
        EXCEPTION_MSG="unable to perform select"
        EXCEPTION_FUNC="$FUNCNAME"
        return 1
      fi
    
    RESULT=$name
    EXCEPTION=$Table__NoException
    EXCEPTION_MSG=""
    EXCEPTION_FUNC=""
    return 0
}

信号の捕捉と処理

例外をキャッチして処理するのにこれが便利だと分かりました。

function Main__interruptHandler() {
    # @description signal handler for SIGINT
    echo "SIGINT caught"
    exit
} 
function Main__terminationHandler() { 
    # @description signal handler for SIGTERM
    echo "SIGTERM caught"
    exit
} 
function Main__exitHandler() { 
    # @description signal handler for end of the program (clean or unclean). 
    # probably redundant call, we already call the cleanup in main.
    exit
} 
    
trap Main__interruptHandler INT
trap Main__terminationHandler TERM
trap Main__exitHandler EXIT

function Main__main() {
    # body
}

# catch signals and exit
trap exit INT TERM EXIT

Main__main "$@"

ヒントとコツ

何らかの理由で動作しない場合は、コードの順序を変更してみてください。順序は重要であり、必ずしも直感的であるとは限りません。

tcsh での作業は考えないでください。関数をサポートしておらず、全体的にひどいものです。

注意: ここで私が書いたようなものを使用しなければならない場合、それは問題がシェルで解決するには複雑すぎることを意味します。別の言語を使用してください。人的要因とレガシーのためにそれを使用する必要がありました。

おすすめ記事