Skip to content

Instantly share code, notes, and snippets.

@rbf
Last active December 21, 2015 00:18
Show Gist options
  • Save rbf/6218734 to your computer and use it in GitHub Desktop.
Save rbf/6218734 to your computer and use it in GitHub Desktop.
List bash array with max line length and custom item separator.
# Usage: echoarraywithmaxwidth <max line length> <array name> [<item separator>] [<line prefix>]
echoarraywithmaxwidth(){
declare -i ea_line_length
ea_separator="${3:-", "}"
ea_result=""
ea_array=()
for (( i = 0; i < "$(eval echo \"\${#${2}[@]}\")"; i++ )); do
ea_array+=("$(eval echo \"\${${2}[${i}]}\")")
done
for word in "${ea_array[@]}"; do
word="${word}${ea_separator}"
[ $((( ${ea_line_length} + ${#word} ))) -ge ${1} ] && ea_result+="\n${4}" && ea_line_length=0
ea_result+="${word}"
ea_line_length+=${#word}
done
echo -e "${ea_result%${ea_separator}}"
}
# GP_BABEL_LANGUAGES=("example with spaces" \
# "afrikaans" "bahasa" "breton" "catalan" "croatian" \
# "czech" "danish" "dutch" "english" "USenglish" "american" "UKenglish" \
# "british esperanto" "estonian" "finnish" "french" "francais" "galician" \
# "austrian" "german" "germanb greek" "hebrew" "magyar" "hungarian" \
# "irish" "italian" "lowersorbian" "norsk" "nynorsk" "polish" "portuges" \
# "portuguese" "brazilian" "brazil romanian" "russian" "scottish" \
# "spanish" "slovak" "slovene" "swedish" "turkish" "uppersorbian" "welsh")
#
# echoarraywithmaxwidth 80 GP_BABEL_LANGUAGES
#
# echoarraywithmaxwidth 40 GP_BABEL_LANGUAGES " - "
#
# exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment