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?
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?
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)
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).