read variable from file in shell script

How to Read Variable from File in Shell Script

Sometimes you may need to read variable from file in shell script. This is a simple requirement but can confuse many developers. In this article, we will learn how to read variable from file in shell script.


How to Read Variable from File in Shell Script

Let us say you have the following file data.txt with variables and their values.

$ cat data.txt
var1=value1
var2=value2
...

Let us say you want to use the variables defined in the above file in your shell script. You can do so by using source or dot(.) before the filename in your shell script. Here is an example to refer to the file with variables from a shell script.

source /home/ubuntu/data.txt
OR
. /home/ubuntu/data.txt

It is similar to importing the file into your shell script. Once you have imported the above file in your shell script, you can get their value by adding $ before their variable names, like $var1, $var2.

Here is an example to read & print variable from filename in shell script. Create a blank shell script.

$ vi read-variable.sh

Add the following lines to it.

#/bin/sh

source /home/ubuntu/data.txt
echo $var1

Save and close the file. Make it an executable.

$ chmod +x read-variable.sh

You can run the shell script as shown below.

$ ./read-variable.sh

In this article, we have learnt how to read variable from file in shell script. You can use this command as per your requirement in your shell script.

Also read:

Shell Script to Print Output in Table Format
How to Change PHP Version in Ubuntu
MySQL Clustered Index
How to Execute Stored Procedure in Python
How to Manage PostgreSQL Views

One thought on “How to Read Variable from File in Shell Script

Leave a Reply

Your email address will not be published. Required fields are marked *