65

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?

codeforester
  • 34,080
  • 14
  • 96
  • 122
The Student
  • 26,271
  • 66
  • 155
  • 257

5 Answers5

91

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
wich
  • 15,963
  • 5
  • 45
  • 70
  • Since when is spacing before and after `=` allowed in shell scripting? – orlp Jan 20 '11 at 16:44
  • 1
    @nightcracker sorry, brainfart, I had already corrected it before I saw your comment – wich Jan 20 '11 at 16:49
  • 1
    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 Jul 05 '17 at 10:51
  • @Jonathan no it won't – wich Jul 05 '17 at 14:46
50

The simplest way is probably:

var=$(< file)

which doesn't create a new process.

nbro
  • 13,796
  • 25
  • 99
  • 185
Diego Torres Milano
  • 61,192
  • 8
  • 106
  • 129
3

I think the easiest way is something like

$ myvar=`cat file`
AlikElzin-kilaka
  • 31,903
  • 30
  • 182
  • 264
giles123
  • 331
  • 7
  • 17
2
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.

jamesbtate
  • 1,329
  • 2
  • 19
  • 25
1

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

variable=$(cat filename)
orlp
  • 106,415
  • 33
  • 201
  • 300
  • 6
    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"` – Dennis Williamson Jan 20 '11 at 18:31