Tuesday, January 30, 2024

[SOLVED] File input in bash script from an array of strings

Issue

Given an array of strings, I need to input each of these strings as a source file into a build script.

  1. 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")
  1. Convert contents of array into one string:
SOURCE_AS_STR=""
for val in "${SOURCES[@]}";
do
    SOURCE_AS_STR+=$val
done
  1. 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.


Solution

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 a

    BUILD_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.



Answered By - user1934428
Answer Checked By - Timothy Miller (WPSolving Admin)