Bash: Insert in a variable a file

hi all
i have a problem in the bash shell. i'd like insert in a variable a file for example :

i have a file datafine.log in this file there is :

17/JUN/2019

i want to insert the value of datafine.log in a variable.
Regards
Frncesco

First, you should notice that funny things ca happen if the content of the file is more than the (probably expected) one line of text. Some caution is advised before you use data in this way therefore.

Aside from these considerations it is quite easy:

var=$( < /path/to/file )

$( .... ) is a subshell which runs the commands inside the brackets and puts it output on the line, similar to a variable expansion. The command < /path/to/file is a simple redirection which means the output is the content of the file.

I hope this helps.

bakunin

1 Like

Note that

var=$( < /path/to/file )

works in ksh, bash, zsh.
The standard shell needs a command like cat

var=$( cat < /path/to/file )

It is safer to only read one line from the file:

IFS= read -r var < /path/to/file

And this works in standard-compliant shells.
The IFS= and the -r force a raw read. By default read strips leading and trailing space and continues with the next line if the line ends with a \ character.