Skip to content

Instantly share code, notes, and snippets.

@YakDriver
Last active Feb 15, 2018
Embed
What would you like to do?
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