86

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?

5 Answers 5

120

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 
Sign up to request clarification or add additional context in comments.

3 Comments

newlines will make the first part try to execute and fail with a command not found error use var=$(cat file | tr -d '\n') to remove all new lines, including any trailing ones
@Jonathan no it won't
Be careful when using this with a single-line file. The resulting array variable will look like a normal one, but you won't be able to easily export it: echo X > f; mapfile -t V < f; echo V is $V; export V; env | grep V=. Note how V is missing from env despite being defined before exporting.
58

The simplest way is probably:

var=$(< file) 

which doesn't create a new process.

5 Comments

This works in Bash and other advanced shells, but not in the Bourne shell.
not cross platform... won't work in sh see stackoverflow.com/questions/7427262/…
Does anyone/anything even still use non-bash sh in 2018? Maybe Dick Tracy's watch??
Warning: no space prior to the “<” (i.e. (< instead of ( <).
This solution does a transformation over 'endline' char on linux.
4
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.

1 Comment

I have a file nammed "log", and $x="`cat log`" results in =2: command not found
4

I think the easiest way is something like

$ myvar=`cat file` 

1 Comment

It's not necessary to export the variable and the spaces around the equal sign won't work.
2

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

variable=$(cat filename) 

2 Comments

It will only strip the final newline. If you seem to be getting the other newlines stripped, it's because you're not quoting the variable on output. echo $variable vs. echo "$variable"
@DennisWilliamson Thanks for the hint, I was about to go crazy finding out why

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.