Reputation: 15294
I encountered this code:
file=$(<filename)
This reads the file from the filename.
My question is how does this work?
I read from this post:
How to use double or single brackets, parentheses, curly braces
It tells me, single parentheses can function as:
- Sub bash execution
- Array construction
But in the case above, I do not know how this explains.
Besides this question, I want to know that why when I do echo $file
, the file content concatenate into one line?
Upvotes: 1
Views: 1165
Reputation: 1621
echo $file
will give you a concatenated output.
Try
echo "$file"
this will give you an output in multiple lines.
Upvotes: 1
Reputation: 799300
$(...)
performs command substitution; the command inside is read and the output from stdout is returned to the script.
<...
is redirection; the contents of the file are read and fed into stdin of the process.
Putting the two together results in an implicit cat
, connecting the stdin of the redirection to the stdout of the command substitution, reading the contents of the file into the script.
Upvotes: 7
Reputation: 5249
You must surround your variable into double quotes, else it will be expanded into command line arguments that will be passed to echo.
If you surround it into double quotes variable will be passed as single argument and echo will display it correctly.
echo "$file"
Upvotes: 2