Given an array of strings, I need to input each of these strings as a source file into a build script.
- Declare the array (the extra space at the end of the filename is deliberate):
SOURCES=( \
"../../header1.h " \
"../../source1.cpp " \
"../../header2.h " \
"../../header3.h " \
...
"./main.cpp")
- Convert contents of array into one string:
SOURCE_AS_STR=""
for val in "${SOURCES[@]}";
do
SOURCE_AS_STR+=$val
done
- Redirect string into a build script:
bash my_build_script.sh < "${SOURCE_AS_STR}"
BASH terminal response: ... No such file or directory
I’ve tried arrays and heredoc strings but I am getting “ambiguous redirect” error as well.
All I needed was to lose the redirect <
and I could do bash my_build_script.sh "${SOURCES[@]}"
as suggested in comments by Paolo.
My problem was the “redirect was ambiguous”, so I didn’t know I could just drop the <
and send the array.
The backslashes (when defining SOURCES
) are unnecessary, but they don’t harm.
In your approach, you are telling bash to use the string stored in SOURCE_AS_A_STRING
as filename and feed the content of this file into the standard input of the script.
You did not specify, how my_build_script.sh
expects the input, so here are various possibilities:
-
If the input is to be processed via stdin, do a
my_build_script.sh <<<$SOURCE_AS_A_STRING
-
If the input should be passed to the script as a parameter, do a
my_build_script.sh "$SOURCE_AS_A_STRING"
-
If the input should be passed to the script via the environment (say, via the environment variable
BUILD_INPUT
), do aBUILD_INPUT=$SOURCE_AS_A_STRING my_build_script.sh
Of course the question is why your scripts expects an input (in whatever way) as a single string, and not as list of file names. This smells like a badly designed script file.
Well surely
...
shouldn’t be in the array should it?Anyway you can use
bash my_build_script.sh "${SOURCES[@]}"
If you want the string to go to the stdin of the command, use a “here string”:
<<<
.You don’t need those backslash characters in the array declaration. Newlines don’t end a
=(...)
variable assignment.