shell dot on steroids https://pagure.io/shellfu

arr.sh 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #!/bin/bash
  2. shellfu import isa
  3. shellfu import pretty
  4. #
  5. # Array utilities
  6. #
  7. # Several utilities for loading and printing Bash arrays.
  8. #
  9. arr__fromcmd() {
  10. #
  11. # Save output lines from command $2.. to array named $1
  12. #
  13. # Usage:
  14. # arr__fromcmd ARRAY CMD [ARG]..
  15. #
  16. # Unlike `mapfile -t <<<"$(command)", this produces zero
  17. # items if command output was empty.
  18. #
  19. local __arr__fromcmd__oarr=$1; shift
  20. local __arr__fromcmd__cmd=("$@")
  21. local __arr__fromcmd__tmp
  22. local es
  23. __arr__val_oarr "$__arr__fromcmd__oarr" || return 2
  24. __arr__fromcmd__tmp=$(mktemp arr__fromcmd.__arr__fromcmd__tmp.XXXXX)
  25. "${__arr__fromcmd__cmd[@]}" > "$__arr__fromcmd__tmp"; es=$?
  26. mapfile -t "$__arr__fromcmd__oarr" <"$__arr__fromcmd__tmp"
  27. rm "$__arr__fromcmd__tmp"
  28. return $es
  29. }
  30. arr__has() {
  31. #
  32. # True if value $1 is in array $2
  33. #
  34. # Usage:
  35. # arr__has VALUE ARRAY
  36. #
  37. local want=$1
  38. local iarr=$2
  39. local copy
  40. local value
  41. local code
  42. __arr__val_iarr "$iarr" || return 2
  43. code=$(declare -p "$iarr"); code=${code/ $iarr=/ copy=}
  44. eval "$code"
  45. for value in "${copy[@]}"; do
  46. test "$value" == "$want" && return 0
  47. done
  48. return 1
  49. }
  50. arr__join() {
  51. #
  52. # Join items in array $2 by string $1
  53. #
  54. # Usage:
  55. # arr__join DELIM ARRAY
  56. #
  57. # Example:
  58. #
  59. # names=( Alice Bob )
  60. # arr__join , names
  61. # # prints 'Alice,Bob'
  62. #
  63. local delim=$1
  64. local iarr=$2
  65. local first=true
  66. local item
  67. local copy
  68. local code
  69. __arr__val_iarr "$iarr" || return 2
  70. code=$(declare -p "$iarr"); code=${code/ $iarr=/ copy=}
  71. eval "$code"
  72. for item in "${copy[@]}"; do
  73. $first || echo -n "$delim"
  74. first=false
  75. echo -n "$item"
  76. done
  77. }
  78. __arr__val_iarr() {
  79. #
  80. # Validate input array named $1
  81. #
  82. local name=$1
  83. set | grep -q "^$name=" || { warn "no such array: $name"; return 2; }
  84. }
  85. __arr__val_oarr() {
  86. #
  87. # Validate output array named $1
  88. #
  89. local name=$1
  90. isa__name "$name" || { warn "invalid array name: $name"; return 2; }
  91. }