Last active
February 15, 2018 20:59
-
-
Save YakDriver/8860c73813b6cd71aa529c77231b76a9 to your computer and use it in GitHub Desktop.
Bash Basics: Reading AND Writing Arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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