alternative to readarray, because it does not work on mac os x

后端 未结 7 2052
挽巷
挽巷 2021-01-17 16:55

I have a varsValues.txt file

cat varsValues.txt
aa=13.7
something=20.6
countries=205
world=1
languages=2014
people=7.2
oceans=3.4

And I wou

7条回答
  •  Happy的楠姐
    2021-01-17 17:25

    Figured I'd toss this in here: https://raw.githubusercontent.com/AdrianTP/new-environment-setup/master/utils/readarray.sh

    #!/bin/bash
    # from: https://peniwize.wordpress.com/2011/04/09/how-to-read-all-lines-of-a-file-into-a-bash-array/
    readarray() {
      local __resultvar=$1
      declare -a __local_array
      let i=0
      while IFS=$'\n' read -r line_data; do
          __local_array[i]=${line_data}
          ((++i))
      done < $2
      if [[ "$__resultvar" ]]; then
        eval $__resultvar="'${__local_array[@]}'"
      else
        echo "${__local_array[@]}"
      fi
    }
    

    I keep this in a "utils" folder in my "new-environment-setup" Github repo, and I just clone it down and import it whenever I need to read a file into an array of lines an array get a new computer or wipe my drive. It should thus act as a backfill for readarray's shortcomings on Mac.

    Import looks like:

    # From: https://stackoverflow.com/a/12694189/771948
    DIR="${BASH_SOURCE%/*}"
    if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi
    . "$DIR/utils/readarray.sh"
    

    Usage looks like readarray "" "".

    Yes it's a little rough. Sorry about that. It may not even work correctly anymore, but it did at one point, so I thought I would share it here to plant the idea of simply...writing your own backfill.

提交回复
热议问题