Skip to content

Instantly share code, notes, and snippets.

@YakDriver
Last active February 15, 2018 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YakDriver/8860c73813b6cd71aa529c77231b76a9 to your computer and use it in GitHub Desktop.
Save YakDriver/8860c73813b6cd71aa529c77231b76a9 to your computer and use it in GitHub Desktop.
Bash Basics: Reading AND Writing Arrays
#!/bin/bash
# It's suprisingly hard to find example of both reading AND writing arrays to files that are compatible with each other.
# This is a mated pair of ways to read and write, respectively.
#
# OUTPUT:
#
# 0
# A line of text
# new_arr[1]: A line of text
#
# an array to write to file
arr[0]=0
arr[1]="A line of text"
# create file based on array, one line per element
# often with arrays, the space is used as a delimiter and with element 1 above, that won't work
printf "%s\n" "${arr[@]}" > array_out.txt
cat array_out.txt
# read the array from file, line per element
# several ways to read the file into an array
readarray -t new_arr < array_out.txt # only with bash 4+
#IFS=$'\n' GLOBIGNORE='*' command eval 'new_arr=($(cat array_out.txt))' # solid old school way
#IFS=$'\n' read -d '' -r -a new_arr < array_out.txt # not recommended - exit 1 but works
# test the results
echo "new_arr[1]: ${new_arr[1]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment