80

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
  • 39,467
  • 16
  • 112
  • 140
The Student
  • 27,520
  • 68
  • 161
  • 264

5 Answers5

114

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
  • 16,709
  • 6
  • 47
  • 72
  • 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
  • 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. – bers Feb 13 '23 at 08:18
55

The simplest way is probably:

var=$(< file)

which doesn't create a new process.

nbro
  • 15,395
  • 32
  • 113
  • 196
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
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.

jamesbtate
  • 1,359
  • 3
  • 19
  • 25
4

I think the easiest way is something like

$ myvar=`cat file`
AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277
giles123
  • 361
  • 7
  • 17
1

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

variable=$(cat filename)
orlp
  • 112,504
  • 36
  • 218
  • 315
  • 9
    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