Reputation: 41163
I have a bash script that I want to read a settings files. Each line of the settings file has a special meaning for the rest of the script (eg line1=source_directory line2=destination_directory)
Is there an easy way to parse the settings file into environment variables I can use in the rest of the script?
Edit: I like the source idea but... I was originally going have a file like this:
/my/source/dir /my/dest/dir
not:
src_dir=/my/source/dir dst_dir=/my/dest/dir
Can I somehow parse the first file?
Upvotes: 1
Views: 504
Reputation: 189317
If your file just has values, you don't really "parse" it.
exec 3<config
read source <&3
read dest <&3
exec 3<-
You might want to add some flags to read
if your values may contain whitespace, etc. I should perhaps change the answer to have read -r
but I encourage you to study the other available flags, too.
Upvotes: 0
Reputation: 1
You can source it
. foo.sh
this will allow you to use all the variables defined in foo.sh
.
You can also invoke using source
keyword
source foo.sh
source: source filename [arguments]
Read and execute commands from FILENAME in the current shell.
Upvotes: 1
Reputation: 361565
A common trick is to source configuration files. On Red Hat systems, for instance, the system scripts in /etc/rc.d
and /etc/sysconfig
do this.
. /etc/prog.conf
This reads them as if they were scripts. This works great if the settings use name=value
form and comments begin with #
.
Caution: Make sure the configuration file is trusted since you're executing it like a script. It should be owned by the same user and group and have the same permissions as parent script.
Upvotes: 1