Hi,
I have a small part of a project which is done as a bash script. bash was selected as an portability issue that works out of the box. In this script I have an exec shell-function, a wrapper around arbitrary commands. I want to have STDOUT, as an addon STDERR and the EXIT-CODE of a specified command.
I'd like to have a clean wrapper, but my solution at the moment is ugly and does not produce clean code at the calling side. Maybe you have some hints to improve it.
In saying "clean" I'm thinking of side effect free programming, i. e. don't get into a mess with global variables and encapsulate all within the _exec function and just have that function to be called. (In the current situation, I have to use an additional line for every extra parameter I'm getting from _exec in the calling function.) I'd like to avoid eval("eval" should better be named "evil") too :).
That's what I have so far:
function _dbg {
# verbose logging here
}
function _fatal {
# fatal error handling here
}
function _exec {
local CMD=$1
local OUT="$( $CMD 2>&1 ;echo "||$?" )"
local EXIT_CODE="${OUT##*||}"
# if no output is there at all [[:space:]]* does
# not match. So do one with space and one without
OUT="${OUT%[[:space:]]*||[0-9]*}"
OUT="${OUT%||[0-9]*}"
OUT="${OUT:-<EMPTY>}"
if [ "$EXIT_CODE" != "0" ]; then
_fatal $ESHELLERR "$EXIT_CODE" "$OUT" "$CMD"
else
_dbg "SHELL EXEC successful CMD: $CMD EXIT_CODE: $EXIT_CODE OUT: $OUT"
fi
echo "$EXIT_CODE||$OUT"
}
function _delete_compatible {
local DIR="$1"
local OUT="$(_exec "rm -rf $DIR")"
local EXIT_CODE="${OUT%||*}"
OUT="${OUT#*||}"
if [ "$EXIT_CODE" == "0" ]; then
_dbg "compatible delete successful"
_success
else
echo "$OUT"
fi
}
Not sure if this one will help me:
Returning Values from Bash Functions | Linux Journal