0

my bash script consists of several functions and I have an option to start from different points in the script. Although you can only start from other steps than the first if a logfile exists. This logfile contains all given parameters during the runs and looks like this:

var1=ABC
var2=123
var3=456
var1=DEF
var4=XYZ
var2=789

As you can see it can happen that variables get different values assigned while the logfile is read. Now I would like to know how I can make my script read through this file at the beginning of my main function so that all following functions work with these variables from the logfile until the variables are changed within a function.

I don't want to assign new names for the variables as they are titled the same in the other functions. I actually just want the file to be read like its content would be written at the beginning of the main function.

function1 {
var1="X"
}
.
.
.
#MAIN
read logfile
function1
...
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
Ueffes
  • 168
  • 12
  • 4
    You can source a file with `.`: `. file` ... There's also `source`, which does the same but works only in `bash`. – Martin Tournoij Oct 30 '14 at 11:13
  • Do you want to load entire log file at the beginning of the script or read it line by line and execute other functions using values so far read? Could there be duplicate values for the same variable as given in your sample? – Sithsu Oct 30 '14 at 12:16
  • possible duplicate of [Bash script - How to reference a file for variables](http://stackoverflow.com/questions/5228345/bash-script-how-to-reference-a-file-for-variables) – tripleee Oct 30 '14 at 12:27
  • i write als variables i get during a run into this logfile and it can happen that some variables are the same but I want it to be like that – Ueffes Oct 30 '14 at 13:40
  • @tripleee I guess you are right. But i didn't know how to look for that... – Ueffes Oct 30 '14 at 13:44

2 Answers2

2

If the file containing var1=ABC etc. is called params.sh for example, you can do this in Bash:

source params.sh

This will behave as if you had pasted the entire contents of params.sh at that location.

If you want to be compatible with other shells, this is equivalent, more portable, but less readable:

. params.sh
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • hmm ok thank you, I guess that is the answer i was looking for. btw if i would want a file from a directory below would it be '../. file' ? – Ueffes Oct 30 '14 at 13:42
  • @Ueffes: yeah, something like that, whatever the relative path is to what you want to load. – John Zwinck Oct 30 '14 at 14:20
0

Run with a . name-of-the-script.

This will pass the environment variables as set in child shell to parent shell.

Sithsu
  • 2,209
  • 2
  • 21
  • 28
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69