11

The output is

/     ext4
/boot ext2
tank  zfs

On each line the delimiter is a space. I need an associative array like:

"/" => "ext4", "/boot" => "ext2", "tank" => "zfs"

How is this done in bash?

4
  • Not at all, unfortunately. You can't have slashes in the keys of associative arrays in bash. What is it you're ultimately trying to achieve, so I can suggest workarounds? Commented May 30, 2015 at 1:23
  • 3
    @Wintermute, pardon? One certainly can; the only character not valid in a key's body is NUL. Did you actually test this claim? Commented May 30, 2015 at 2:24
  • @CharlesDuffy arr[/]=bar doesn't work for me with bash 4.3. Nor does anything else with / in it. bash: /: syntax error: operand expected (error token is "/") is the error. Quotes don't help. Commented May 30, 2015 at 10:23
  • 1
    @CharlesDuffy Oh, I was being stupid, my bad. Forgot the declare -A/didn't remember that it was necessary. I'll go stand in the corner now. Commented May 30, 2015 at 10:27

1 Answer 1

19

If the command output is in file file, then:

$ declare -A arr=(); while read -r a b; do arr["$a"]="$b"; done <file

Or, you can read the data directly from a command cmd into an array as follows:

$ declare -A arr=(); while read -r a b; do arr["$a"]="$b"; done < <(cmd)

The construct <(...) is process substitution. It allows us to read from a command the same as if we were reading from a file. Note that the space between the two < is essential.

You can verify that the data was read correctly using declare -p:

$ declare -p arr
declare -A arr='([tank]="zfs" [/]="ext4" [/boot]="ext2" )'
Sign up to request clarification or add additional context in comments.

1 Comment

Wow this just blew my mind, I definitely need to read up on arrays.

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.