Is there an elegant way to store and evaluate return values in bash scripts?

后端 未结 6 2116
傲寒
傲寒 2020-12-01 20:03

I have a rather complex series of commands in bash that ends up returning a meaningful exit code. Various places later in the script need to branch conditionally on whether

6条回答
  •  醉话见心
    2020-12-01 20:21

    The simple solution:

    output=$(complex_command)
    status=$?
    
    if (( status == 0 )); then
        : stuff with "$output"
    fi
    
    : more code
    
    if (( status == 0 )); then
        : stuff with "$output"
    fi
    

    Or more eleganter-ish

    do_complex_command () { 
        # side effects: global variables
        # store the output in $g_output and the status in $g_status
        g_output=$(
            command -args | commands | grep -q trigger_word
        )
        g_status=$?
    }
    complex_command_succeeded () {
        test $g_status -eq 0
    }
    complex_command_output () {
        echo "$g_output"
    }
    
    do_complex_command
    
    if complex_command_succeeded; then
        : stuff with "$(complex_command_output)"
    fi
    
    : more code
    
    if complex_command_succeeded; then
        : stuff with "$(complex_command_output)"
    fi
    

    Or

    do_complex_command () { 
        # side effects: global variables
        # store the output in $g_output and the status in $g_status
        g_output=$(
            command -args | commands
        )
        g_status=$?
    }
    complex_command_output () {
        echo "$g_output"
    }
    complex_command_contains_keyword () {
        complex_command_output | grep -q "$1"
    }
    
    if complex_command_contains_keyword "trigger_word"; then
        : stuff with "$(complex_command_output)"
    fi
    

提交回复
热议问题