How can I read a file and redirect it to a variable?

LinuxShellScripting

Linux Problem Overview


I have a file with a word written on it. I want my script to put that word in a variable.

How can I do that?

Linux Solutions


Solution 1 - Linux

in several of a million ways...

simplest is probably

my_var=$(cat my_file)

If you use bash and you want to get spiffy you can use bash4's mapfile, which puts an entire file into an array variable, one line per cell

mapfile my_var < my_file

Solution 2 - Linux

The simplest way is probably:

var=$(< file)

which doesn't create a new process.

Solution 3 - Linux

I think the easiest way is something like

$ myvar=`cat file`

Solution 4 - Linux

var="`cat /path/to/file`"

This is the simple way. Be careful with newlines in the file.

var="`head -1 /path/to/file`"

This will only get the first line and will never include a newline.

Solution 5 - Linux

I think it will strip newlines, but here it is anyway:

variable=$(cat filename)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThe StudentView Question on Stackoverflow
Solution 1 - LinuxwichView Answer on Stackoverflow
Solution 2 - LinuxDiego Torres MilanoView Answer on Stackoverflow
Solution 3 - Linuxgiles123View Answer on Stackoverflow
Solution 4 - LinuxjamesbtateView Answer on Stackoverflow
Solution 5 - LinuxorlpView Answer on Stackoverflow