Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

set variables in a for loop 1

Status
Not open for further replies.

nabana2

Technical User
Sep 26, 2005
21
ZA
Hi

I am writing a bash script in which i need to set variables in a for loop.
This doesn't seem to work and I'm not sure why it is any different to setting them any where else in the script.

I have tried:

Code:
array=(1 2 3 4 5 6 7 8 9); for i in ${array[*]}; do "V$i"="test"; done

but i just get a series of:
-bash: V1=test: command not found

V1="test" would work fine so why cant i do it in a for loop?

Thank you

 
Thanks very much Feherke.
I'm half way there.

I am now struggling to use the value of my variable in an if statement.
I haven't been able to find any info on the internet for what I'm trying to do.

My objective is to assign a default value to a set of variables if they have a null value.

Code:
for i in V1 V2 V3 V4 V5; do
  eval echo \$$i; 
  if [ -z \$$i ]; then 
    eval "$i=test";
    eval echo \$$i;
  fi;
done

Thank you
 
Hi

man bash said:
Parameter Expansion

[gray]...[/gray]

${parameter:=word}
Assign Default Values. If parameter is unset or
null, the expansion of word is assigned to parame­
ter. The value of parameter is then substituted.
Positional parameters and special parameters may
not be assigned to in this way.
For just 5 variables I would do :
Code:
: ${V1:=test}
: ${V2:=test}
: ${V3:=test}
: ${V4:=test}
: ${V5:=test}
But back to our yesterday code :
Code:
for i in ${array[*]}; do eval "[red]: \${[/red]V$i[red]:[/red]=test[red]}[/red]"; done

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top