Cannot get erlang escript exit code if the code is not 0

400 views Asked by At

According to the manual of erlang http://erlang.org/doc/man/escript.html:

If the main/1 function in the script returns successfully,the exit status for the script is 0. If an exception is generated during execution, a short message is printed and the script terminates with exit status 127.

To return your own non-zero exit code, call halt(ExitCode), for example:

halt(1).

but, I called halt(1) to return the exit status 1 to caller, the caller cannot get the exit code, and commands below the $ERTS_DIR/bin/escript myscript in my shell script is not running. by the way, if myscript exit normally, the exit code 0 is received, and commands below the $ERTS_DIR/bin/escript myscript is running. what can I do for this?

2

There are 2 answers

0
legoscia On BEST ANSWER

It sounds like the caller is a shell script using set -e, meaning that it will exit if any command returns a non-zero exit code.

One thing you could do is wrapping the call in an if:

if $ERTS_DIR/bin/escript myscript; then
    echo "the escript ran successfully"
else
    echo "the escript failed with exit code $?"
fi

If you only want to do something special on failure, put a ! in front:

if ! $ERTS_DIR/bin/escript myscript; then
    echo "the escript failed"
fi
1
Pouriya On

It works for me. Let's run an example:

~ $ echo $? # Using $? you can see last exit code in the shell
0

~ $ erl
Erlang/OTP 19 [erts-8.3] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.3  (abort with ^G)
1> halt(1).
~ $ echo $?
1

~ $ cat test.script 
-module(test).
-export([main/1]).

main(_) ->
    halt(127).


~ $ escript test.script
~ $ echo $?
127