Reading an array from an input file in bash

I am trying to clear the code that I wrote to run several programs for files in an array in bash (version 4.2.46). In the scripts that I clean, I use an array with file names as keys and their relative paths as values ​​(I know that there are no extensions in the code below, they are assumed and / or added by separate programs). This array can become quite large, and therefore I want to separate it from the rest of my code in order to improve the readability of programs.

script I am currently using an input file to read:

#!/bin/bash

mapfile -t FILE <$1

declare -A fileArray

while read line; do
    key=$(cut -d'=' -f1 <<< $line)
    value=$(cut -d'=' -f2 <<< $line)
    fileArray[$key]=$value
    echo "Key $key : Value ${fileArray[$key]}"
done <$1

echo "all keys : ${!fileArray[@]}"

, , '=', MyArray - myArray, , . . ():

foo_bar1=foo1/foo_bar1
foo_bar2=foo2/foo_bar2
foo_bar3=foo3/foo_bar3

, , , , , , . , ( ), , .

#!/bin/bash
declare -A fileArray=(
[foo_bar1]='foo1/foo_bar1'
[foo_bar2]='foo2/foo_bar2'
[foo_bar3]='foo3/foo_bar3'
)

- , ?

.

EDIT: , source ( ) , . script, myScript.sh input.sh:

#!/bin/bash
source $1
declare -p fileArray

, , , .

+4
2

line , IFS, = ,

#!/usr/bin/env bash

declare -A fileArray

# Setting IFS value as '=' to delimit read on this character
while IFS== read -r key value; do
    fileArray["$key"]="$value"
done < file

declare -p fileArray

, , , , .

declare -A fileArray=([foo_bar2]="foo2/foo_bar2" [foo_bar3]="foo3/foo_bar3" [foo_bar1]="foo1/foo_bar1" )
+2

:

#!/bin/bash

. <(
awk -F'=' '
BEGIN { print "declare -A ARRAY=(" }
{ print "[" $1 "]=\"" $2 "\"" }
END { print ")" }' inputfile )

echo "all keys : ${!ARRAY[@]}"

:

all keys : foo_bar2 foo_bar3 foo_bar1

:

AWK script

declare -A ARRAY=(
[foo_bar1]="foo1/foo_bar1"
[foo_bar2]="foo2/foo_bar2"
[foo_bar3]="foo3/foo_bar3"
)

and the part . <( ... )replaces the process to assign an array as you expect.

+2
source

Source: https://habr.com/ru/post/1695687/


All Articles