1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- #!/bin/bash
-
- shellfu import isa
- shellfu import pretty
-
- #
- # Array utilities
- #
- # Several utilities for loading and printing Bash arrays.
- #
-
- arr__fromcmd() {
- #
- # Save output lines from command $2.. to array named $1
- #
- # Usage:
- # arr__fromcmd ARRAY CMD [ARG]..
- #
- # Unlike `mapfile -t <<<"$(command)", this produces zero
- # items if command output was empty.
- #
- local __arr__fromcmd__oarr=$1; shift
- local __arr__fromcmd__cmd=("$@")
- local __arr__fromcmd__tmp
- local es
- __arr__val_oarr "$__arr__fromcmd__oarr" || return 2
- __arr__fromcmd__tmp=$(mktemp arr__fromcmd.__arr__fromcmd__tmp.XXXXX)
- "${__arr__fromcmd__cmd[@]}" > "$__arr__fromcmd__tmp"; es=$?
- mapfile -t "$__arr__fromcmd__oarr" <"$__arr__fromcmd__tmp"
- rm "$__arr__fromcmd__tmp"
- return $es
- }
-
- arr__has() {
- #
- # True if value $1 is in array $2
- #
- # Usage:
- # arr__has VALUE ARRAY
- #
- local want=$1
- local iarr=$2
- local copy
- local value
- local code
- __arr__val_iarr "$iarr" || return 2
- code=$(declare -p "$iarr"); code=${code/ $iarr=/ copy=}
- eval "$code"
- for value in "${copy[@]}"; do
- test "$value" == "$want" && return 0
- done
- return 1
- }
-
- arr__join() {
- #
- # Join items in array $2 by string $1
- #
- # Usage:
- # arr__join DELIM ARRAY
- #
- # Example:
- #
- # names=( Alice Bob )
- # arr__join , names
- # # prints 'Alice,Bob'
- #
- local delim=$1
- local iarr=$2
- local first=true
- local item
- local copy
- local code
- __arr__val_iarr "$iarr" || return 2
- code=$(declare -p "$iarr"); code=${code/ $iarr=/ copy=}
- eval "$code"
- for item in "${copy[@]}"; do
- $first || echo -n "$delim"
- first=false
- echo -n "$item"
- done
- }
-
- __arr__val_iarr() {
- #
- # Validate input array named $1
- #
- local name=$1
- set | grep -q "^$name=" || { warn "no such array: $name"; return 2; }
- }
-
- __arr__val_oarr() {
- #
- # Validate output array named $1
- #
- local name=$1
- isa__name "$name" || { warn "invalid array name: $name"; return 2; }
- }
|