On Sat, Sep 07, 2024 at 22:00:27 +0000, Quaeryth wrote:
> A query like "site:stackoverflow.com bash how to read file into variable" via
> Google or DuckDuckGo (and maybe other search engines) usually points me in
> the right direction. Good luck with your experiments!

What kind of file?
What kind of variable?
What are you planning to do with the variable after you've stored data
in it?

The fundamental problem with this question is that bash variables *can't*
store all kinds of data.  Specifically, they are unable to store the NUL
byte (ASCII 0x00), so storing any kind of binary file is off the table.

So, that leaves text files.  You can, in theory, store a text file in
a bash variable -- but why?  What's the point?  Are you going to copy
that data out to another file?  If so, you'd be better off just copying
the original text file with the cp command, instead of reading the data
into a shell string variable and then writing it back out.  Bash is
abysmally *slow* at such things.  Running cp would most likely be faster,
for non-tiny files, even if you have to run it several times.

But maybe this is an X-Y problem, and the real question is something
like "I want to iterate over the lines of a file.  For each line, I
want to do ____."

In that case, reading the entire file into a string variable is a poor
first step.  Now, you *might* read the entire file into an *array*
variable (one line per array element), and then iterate over the array.
That's not the worst thing you could do.

But even that may not be necessary.  If you don't need to pre-read the
entire contents, then don't.  Just read one line at a time, and process
each line as you read it.

That's Bash FAQ #1.  <https://mywiki.wooledge.org/BashFAQ/001>

Reply via email to