Boston Linux & Unix (BLU) Home | Calendar | Mail Lists | List Archives | Desktop SIG | Hardware Hacking SIG
Wiki | Flickr | PicasaWeb | Video | Maps & Directions | Installfests | Keysignings
Linux Cafe | Meeting Notes | Linux Links | Bling | About BLU

BLU Discuss list archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Discuss] Bourne Shell variable assignment question



>On 12/15/2011 04:31 PM, Jerry Feldman wrote:
>Just want to simplify.
>#!/bin/bash
>varname=myvar
>varvalue=foo
>--- do something to create myvar.
>myvar=$varvalue
>echo $myvar


I think 'declare' might be what you were looking for, although AFIACT it's not part of Bourne.? But this works with BASH when invoked as 'sh'.? (Note needing to reset IFS midstream so that declare doesn't throw away the = it needs..)


[root at kressin01v ~]# cat myvars
var1=foo
var2=bar
var3=baz
[root at kressin01v ~]# cat readvar.sh
#!/bin/sh
#
OLDIFS="$IFS"
IFS="="
echo "BEFORE"
echo "====="
set | grep "^var"
echo "====="
while read myvar myvalue
do
??????? echo "$myvar: $myvalue"
??????? IFS="$OLDIFS"
??????? declare $myvar="$myvalue"
??????? IFS="="
done

echo "AFTER"
echo "====="
set | grep "^var"
echo "====="

echo "var1: $var1"
echo "var2: $var2"
echo "var3: $var3"
[root at kressin01v ~]# cat myvars | ./readvar.sh
BEFORE
=====
=====
var1: foo
var2: bar
var3: baz
AFTER
=====
var1=foo
var2=bar
var3=baz
=====
var1: foo
var2: bar
var3: baz
[root at kressin01v ~]#

I could see this (rather than sourcing directly) being potentially useful if you didn't know what variables would be in the file and wanted to keep a list or something without rereading the file.? Though there are surely better / less kludgy ways of accomplishing that particular goal as well.

-Dan



BLU is a member of BostonUserGroups
BLU is a member of BostonUserGroups
We also thank MIT for the use of their facilities.

Valid HTML 4.01! Valid CSS!



Boston Linux & Unix / webmaster@blu.org