[Discuss] Bourne Shell variable assignment question

Gordon Ross gordon.w.ross at gmail.com
Thu Dec 15 23:09:07 EST 2011


On Thu, Dec 15, 2011 at 3:57 PM, Jerry Feldman <gaf at blu.org> wrote:
> I have not done my homework on this as much as I should.
> A coworker needs to set variable names and values input from another
> file. Normally, I would source that file, but he specifically wants to
> parse the file.
> So, in simple terms, he has a file that has something like:
> var1=foo
>
> Instead of sourcing he wants to parse the file using readline so he
> reads the variable name, then he wants to assign a variable of the same
> name.
> So, in his code he has something like
> readline
> ... - code to parse the line
> Where varname contains the variable name(eg var1), and value contains
> the value(eg foo)
>
> --
> Jerry Feldman <gaf at blu.org>
> Boston Linux and Unix
> PGP key id:3BC1EB90
> PGP Key fingerprint: 49E2 C52A FC5A A31F 8D66  C0AF 7CEA 30FC 3BC1 EB90

Here's a reasonable method, snipped from some
scripts I wrote a while back.   Hope it helps...


USAGE="FIX ME"

parse_config()
{
    case "$1" in
	ip_addr=*)	ip_addr="${1#*=}";;
	netmask=*)	netmask="${1#*=}";;
	dns_srv1=*)	dns_srv1="${1#*=}";;
	dns_srv2=*)	dns_srv2="${1#*=}";;
	dns_dom=*)	dns_dom="${1#*=}";;
	*)		echo $USAGE >&2; exit 1;;
    esac
}

print_config()
{
  echo "ip_addr=$ip_addr"
  echo "netmask=$netmask"
  echo "dns_srv1=$dns_srv1"
  echo "dns_srv2=$dns_srv2"
  echo "dns_dom=$dns_dom"
}

while read line
do
  parse_config "$line"
done < "$config_file"


# Here is some test output, given the input:
ip_addr=1.2.3.4
dns_srv1=1.2.3.1
$ config_file=/tmp/fubar bash /tmp/parse.ksh
ip_addr=1.2.3.4
netmask=
dns_srv1=1.2.3.1
dns_srv2=
dns_dom=



More information about the Discuss mailing list