1

I want to create an associative array in Bash with file names derived from a glob as keys. Here is what I am doing:

declare -A file_hash
for file in *; do
  file_hash+=([$file]=1)
done

I am curious to see if there is a more straightforward way of doing the same thing, somewhat like how we initialize a normal array this way:

file_array=(*)

One of the ideas I got from another post on SO is:

file_array=(*)
declare -A file_hash=( $(echo ${file_array[@]} | sed 's/[^ ]*/[&]=&/g') )

Is that the best way?

1
  • 2
    Inspired from the echo method, this works OK in some tests, but requires eval : declare -A filehash; eval $(printf 'filehash+=(["%s"]=1);' *.txt) Commented Mar 6, 2017 at 0:44

1 Answer 1

2

Your loop is the correct way to do this. Anything else risks not properly handling filenames containing characters that the shell may treat specially, namely whitespace (and newlines in particular) and glob metacharacters like *, [], ?, etc.

file_array=(*) works as a shortcut for the longer, more explicit form

file_array=([0]=file1 [1]=file2 ...)

because the indices 0, 1, ... can be inferred from the sequence of files from the glob expansion. With an associative array, you cannot make any such assumption, and the keys and values must be given explicitly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.