7

I have a helper function:

function error_exit
{
    /opt/aws/bin/cfn-signal ...
    exit 1
}

This helper function is used to signal an error. Here is an example of usage:

/opt/aws/bin/cfn-init -s .. || error_exit 'Failed to run cfn-init'

The cfn-init command takes a lot of parameters which isn't relevant for the question. When the command returns a non-null value and possibly an error message to the error output, I would like to get the error message and include it to the error_exit method as a parameter. Is this possible? If not, how would you implement a helper method in bash which makes it possible to get the source error message?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
tronda
  • 307
  • 3
  • 12
  • In the context of CloudFormation's stock templates, from which this looks to derive, also consider setting 'DisableRollback' with `--disable-rollback` in the CLI tools. Also use `cfn-init`'s `-v` flag to get verbose output. – Christopher Jul 23 '12 at 13:22

2 Answers2

7

You can redirect the error output to a file and then retrieve that output:

trap "rm -f /tmp/cfn-error.txt" 0 1 2 3 15
/opt/aws/bin/cfn-init -s ... 2>/tmp/cfn-error.txt ||
    error_exit $(</tmp/cfn-error.txt)

You should always clean up your mess, so don't forget to delete any temp files you create.

Arcege
  • 22,287
  • 5
  • 56
  • 64
1

You can also do this by redirection:

# run_cmd 'error message' cmd -foo "${params[@]}"
run_cmd() {
    local e r m=$1
    shift
    exec 6>&1
    e=$("$@" 2>&1 >&6)
    r=$?
    exec 6>&-
    ((r)) || return 0
    error_exit "$m" "$e"
}

So you would use:

run_cmd 'Failed to run cfn-init' /opt/aws/bin/cfn-init -s ..

The line: e=$("$@" 2>&1 >&6) first directs stderr to stdout, which in the context of $(..) is the output we're capturing. Then stdout is directed to where it originally went when we started the function.

Of course, you can make error_exit additionally take the exit status, and call it with eg: error_exit "$m" "$r" "$e"

steveL
  • 71
  • 1