I have some bash code that currently works correctly. However the syntax is somewhat verbose and I would appreciate any advice on how to shorten the following bash code.
For complete reference the entire script can can be found here: https://gist.github.com/sacvalleytech/951f9eb98625f983f8f4dab623f5918b
# find new deps
# $1 -> file to search for dependencies
# $2 -> array of previous dependency changes (from siblings; used to invalidate cache); code not shown
# $3 -> hierarchy of dependencies (for circular ref checking); code not shown
DEP_OUT=( "$(changes "$DEP" "${DEP_OUT[*]}" "${DEP_HIERARCHY[*]}")" )
# >>> its really annoying to do this
# >>> to capture the return code before sorting the array
# >>> sorting the array BEFORE causes the return code to be lost
[ "$?" -eq 0 ] && DEP_CHANGED=true
# sort values | normalize paths | uniq values
DEP_OUT=( $(printf "%s\n" "${DEP_OUT[@]}" | sort | trim | uniq) )
UPDATE:
Based on the comments I have come up with the following solution.
function format_array {
if [ -t 0 ]; then
local ARRAY_IN=( $@ )
else
readarray ARRAY_ARGS < /dev/stdin
local ARRAY_IN=( $@ ${ARRAY_ARGS[@]} )
fi
echo $(printf "%s\n" "${ARRAY_IN[@]}" | sort | normalize_paths | uniq)
}
shopt -s lastpipe
shopt -so pipefail
DEP_OUT=( $(changes "$DEP" "${DEP_OUT[*]}" "${DEP_HIERARCHY[*]}" | format_array "${DEP_OUT[*]}") ) && \
DEP_CHANGED=true
This was essential to getting the correct return code propagated.
(I thought one of the comments mentioned this briefly, it looks to have been removed)
shopt -s lastpipe
shopt -so pipefail