Ubuntu – How to read a variable from a file

bashscripts

I want to insert in my script a value (string) that I would read from a text file.

For example, instead of:

echo "Enter your name"
read name

I want to read a string from another text file so the interpreter should read the string from the file and not the user input.

Best Answer

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
Related Question