- Double-quote your variables when you use them. Otherwise they'll break if you pass values that contain whitespace. Also, there's no need for that subshell. So instead of
if (usageSliceArr $1 $2 $3); then you should write if usageSliceArr "$1" "$2" "$3"; then
- Use
-ne to compare numbers, != for strings
- Don't forget there's https://shellcheck.net/
- Double-quote your variables when you use them
- Put the usage message inside the function that does the work, so that the code becomes self-documenting
- Write error messages to stderr rather than stdout
- Consider writing commands as shell scripts that live in your
$PATH rather than functions available only if your ~/.bash_profile is executed
- Did I mention you should double-quote your variables when you use them?
Here's one approach:
########################################################################
# slicearr name index count
#
# Return <count> space-separated and tokenised elements from the <name>
# array starting at <index>
#
slicearr() {
if [ $# -ne 3 ]
then
echo 'Usage: name index count' >&2
exit 1
fi
declare -n name=$1
printf "%s " "${name[@]:$2:$3}"; echo
}
The relevance of the space-separated and tokenised clause applies to your original code, too. Consider an array
a=( one two 'twenty three' )
The "twenty three" will be extracted as a single element but returned as two space-separated values "twenty" and "three".