dbmitch dbmitch - 5 months ago 10
Bash Question

using grep lookup/cut function instead of source to load config file in bash

I have a script that I'm using now that loads all my config variables in by means of

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
directive to achieve the same results. Is that any different or safer than
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
function I found in a shell scripting book. It basically used
, a delimiter and
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:


Sample function (from notes)

lookup() {
grep "^$1$TAB" "$2" | cut -f2


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() {

   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.