0

I've been struggling with this problem for a while. Let's assume I have two scripts.

  1. test1.sh
  2. test2.sh

The code in test1.sh is the following:

array1="/dir/file1.txt /dir/file2.txt /dir/file3.txt"

array2="/dir/file4.txt /dir/file5.txt /dir/file6.txt"

./test2.sh "$array1" "$array2"

The code in test2.sh is the following:

echo $1
echo $2

This works fine, and prints the two arrays correctly:

/dir/file1.txt /dir/file2.txt /dir/file3.txt
/dir/file4.txt /dir/file5.txt /dir/file6.txt

For the project I am working on I have to put the execution code in a variable so that I can run it with the eval-command. I've tried it as follows:

array1="/dir/file1.txt /dir/file2.txt /dir/file3.txt"
array2="/dir/file4.txt /dir/file5.txt /dir/file6.txt"

com="./test2.sh "$array1" "$array2" "

eval $com

However, this returns:

/dir/file1.txt
/dir/file2.txt   

How do I get it to give the same input? I've been struggling with this for a while now and Im honestly pretty stuck. I believe it is caused by the many quatation marks in com-variable, but I am not sure.

Many thanks, Patrick

PWvanZalm
  • 1
  • 1
  • 1
    See [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050). Arrays are the right thing. `eval` is not (which [BashFAQ #48](http://mywiki.wooledge.org/BashFAQ/048) goes into depth on). – Charles Duffy Sep 08 '21 at 22:07
  • 1
    That said, none of your variables are actually arrays at all. `"string1 string2 string3"` is just a string -- bash _has_ arrays, but you aren't using them. – Charles Duffy Sep 08 '21 at 22:07
  • BTW, "how do I pass multiple arrays on a command line?" is a separate entry in our Q&A knowledgebase -- it's covered at [pass multiple arrays as arguments to a bash script](https://stackoverflow.com/questions/43686878/pass-multiple-arrays-as-arguments-to-a-bash-script), f/e. – Charles Duffy Sep 08 '21 at 22:12

1 Answers1

1

Make com an array, and you don't need eval.

#!/usr/bin/env bash
#              ^^^^- NOT /bin/sh. Run with "bash yourscript", not "sh yourscript"

# none of these are actually arrays; they're just misleadingly-named strings
array1="/dir/file1.txt /dir/file2.txt /dir/file3.txt"
array2="/dir/file4.txt /dir/file5.txt /dir/file6.txt"

# This is an actual array.
com=( ./test2.sh "$array1" "$array2" )

# Expand each element of the array into a separate word of a simple command
"${com[@]}"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441