I have a script that I'm using now that loads all my config variables in by means of source
command. It's simple quick and effective. But i understand that it's not a very secure option.
I've read that I can use the $include
directive to achieve the same results. Is that any different or safer than source
or are they essentially the same?
As a final alternative if the above two options are not safe ones, I'm trying to understand a lookup
function I found in a shell scripting book. It basically used grep
, a delimiter and cut
to perform a variable name lookup from the file and retrieve the value. This seems safe and I can use it to modify my scripts.
It almost works as is. I think I just need to change the delimiter to "=" from $TAB but I'm not sure how it works or if it even will.
My config file format:
Param=value
Sample function (from notes)
lookup() {
grep "^$1$TAB" "$2" | cut -f2
}
Usage:
lookup [options] KEY FILE
-f sets field delimiter
-k sets the number of field which has key
-v specifies which field to return
I'm using Debian version of Raspbian Jessie Lite in case that matters on syntax.
Instead of grep
and cut
you should consider using awk
that can do both search and cut operations based on a given delimiter easily:
lookup() {
key="$1"
filename="$2"
awk -F= -v key="$key" '$1 == key{print $2}' "$filename"
# use this awk if = can be present in value part as well
# awk -v key="^$key=" '$0 ~ key && sub(key, "")' "$filename"
}
This can be called as:
lookup search configfile.txt
-F=
sets delimiter as =
for awk command.
Also note that $1
and $2
inside single quotes are columns #1 and #2 and one shouldn't be confused with positional shell variables $1
, $2
etc.
You should look into getopts
to make it accept -f
, -k
etc type arguments.