0

I have a complex data structure in Bash like this:

Test1_Name="test 1"
Test1_Files=(
  file01.txt
  file02.txt
)
Test2_Name="test 2"
Test2_Files=(
  file11.txt
  file12.txt
)
TestNames="Test1 Test2"

In my improved script, I would like read the files from disk. Each test resides in a directory.

So I have a Bash snippet reading directories and reading all the file names. The result is present in an array: $Files[*].

How can I copy that array to an array prefixed with the test's name. Let's assume $TestName holds the test's name.

I know how to create a dynamically named array:

for $Name in $TestNames; do
  declare -a "${TestName}_Files"
done

Will create e.g. Test1_Files and Test2_Files. The variables are of type array, because I used -a in declare.

But how can I copy $Files[*] to "${TestName}_Files" in such a loop?

I tried this:

declare -a "${TestName}_Files"=${Files[*]}

But it gives an error that =file01.txt is not a valid identifier.

0

1 Answer 1

2

You'll want to use newarray=( "${oldarray[@]}" ) to keep the array elements intact. ${oldarray[*]} will involve word splitting, which will break at least with elements containing white space.

However, the obvious declare -a "$name"=("${oldarray[@]}") doesn't work, with the parenthesis quoted or not. One way to do it seems to be to use a name ref. This would copy the contents of old to new, where the name of new can be given dynamically:

#!/bin/bash
old=("abc" "white space")
name=new

declare -a "$name"        # declare the new array, make 'ref' point to it
declare -n ref="$name"    

ref=( "${old[@]}" )       # copy

#unset -n ref             # unset the nameref, if required
declare -p "$name"        # verify results
Sign up to request clarification or add additional context in comments.

2 Comments

What is the purpose of declare -p "$name"?
@Paebbels, just to print out the new copy to verify the result is correct

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.