lacrosse1991
lacrosse1991

Reputation: 3162

why can I not save the output of this awk statement to a variable

I am currently trying to make a variable name that would consist of another variable

while [ "$countf" -le 9 ]; do
    vname=$( echo fcp"$countf" )
    $vname=$( awk -F, -vs="\$fc$countf" '{for (i=1;i<=NF;i++)if($i~"^"s"$"){print i;exit;}}{print "not found"}' <<< $first_line )
    countf=$(( countf + 1 ))
done

although when I go to execute the the script that includes the code, something along the lines of the following is outputted:

fcp1=not: command not found

fcp1 being the content of the vname variable. I've tried several different solutions but have not gotten anything to work yet as of right now, if someone could point out what I am doing wrong though I would really appreciate it, thanks.

Upvotes: 0

Views: 112

Answers (2)

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 184995

You've made a mistake, instead of

$vname=$(... )

you should use :

vname=$(... )

You can't use $ in the left of assignation like this.

A workaround is to use declare if you want to do indirect variable references :

$ x=var
$ declare $x=test
$ echo $var
test

NOTE

As mentioned in discussion in this thead, don't use eval to do this. eval is a common misspelling of evil. See http://mywiki.wooledge.org/BashFAQ/048

Upvotes: 7

Ed Morton
Ed Morton

Reputation: 203209

You need to use eval if you're going to build a variable name from parts like that:

$ cat tst.sh
countf=0
while (( $countf <= 2 ))
do
    vname="fcp${countf}"
    eval $vname="\$(date)"

    countf=$(( countf + 1 ))
    sleep 1
done

echo "$fcp0"
echo "$fcp1"
echo "$fcp2"

$ ./tst.sh
Mon Nov 19 21:22:05 CST 2012
Mon Nov 19 21:22:06 CST 2012
Mon Nov 19 21:22:08 CST 2012

but you should seriously consider an array instead:

$ cat tst.sh
countf=0
while (( $countf <= 2 ))
do
    fcpArr[$countf]="$(date)"

    countf=$(( countf + 1 ))
    sleep 1
done

echo "${fcpArr[0]}"
echo "${fcpArr[1]}"
echo "${fcpArr[2]}"

$ ./tst.sh
Mon Nov 19 21:22:48 CST 2012
Mon Nov 19 21:22:50 CST 2012
Mon Nov 19 21:22:51 CST 2012

Upvotes: 0

Related Questions