How do I read a variable from a file?

Solution 1:

To read variables from a file we can use the source or . command.

Lets assume the file contains the following line

MYVARIABLE="Any string"

we can then import this variable using

#!/bin/bash

source <filename>
echo $MYVARIABLE

Solution 2:

Considering that you want all the content of your text file to be kept in your variable, you can use:

#!/bin/bash

file="/path/to/filename" #the file where you keep your string name

name=$(cat "$file")        #the output of 'cat $file' is assigned to the $name variable

echo $name               #test

Or, in pure bash:

#!/bin/bash

file="/path/to/filename"     #the file where you keep your string name

read -d $'\x04' name < "$file" #the content of $file is redirected to stdin from where it is read out into the $name variable

echo $name                   #test

Solution 3:

From within your script you can do this:

read name < file_containing _the_answer

You can even do this multiple times e.g. in a loop

while read LINE; do echo "$LINE"; done < file_containing_multiple_lines

Solution 4:

name=$(<"$file") 

From man bash:1785, this command substitution is equivalent to name=$(cat "$file") but faster.