0

I have a file stored in a location /x/y/z/file.txt. There is only an unsigned integer stored in this file.

How would I read it and store it into a variable?

davide-pi
  • 127
  • 7

2 Answers2

1

You can do the following:

var=$(cat /x/y/z/file.txt)

The above command will print the file and assign the output to the var variable.

Another thing you can do, if you want to explicitly grab only the first line:

var=$(head -1 /x/y/z/file.txt)

Itai Ganot
  • 10,644
  • 29
  • 93
  • 146
  • The second method looks better for me. But is it $var or only var? – Karthik Srinivas Mar 28 '20 at 07:56
  • It’s only “var” when populating the variable and then when you want to access the variable’s content, then you use “$var” or even better “${var}” - if the first line contains a string with spaces then writing it like so will make sure that spaces are also included as part of the string. – Itai Ganot Mar 28 '20 at 09:06
0

Another option is to use the read builtin command:

IFS= read -r var </x/y/z/file.txt

The IFS= and -r bits are there to disable some "helpful" things read does by default -- removing whitespace at the beginning and end of the line (the IFS= prefix disables this), and processing backslashes as escape/continuation markers (the -r option disables this).

Gordon Davisson
  • 11,216
  • 4
  • 28
  • 33