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
Related posts:
How to Make POST Request with cURL
How to Run Multiple Commands in Linux
How to Install MongoDB in Ubuntu 18.04/20.04
How to Check Supported TLS/SSL Version in Linux
How to Run Shell Script as Cron Job
How to Convert Docx to PDF in Linux
How to Get Unique IP Address from Log File
How to Test If Variable is Number in Shell Script

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.
# config file
#works
foo=bar
# does not work
foo = bar