Below is the issue I am having.
I have a few variables which have certain values in them like
var1=23
var2=46
var3=78 etc...
I want to save these values with the help of a for loop in a single variable so that I can use it later,beacuse a few lines down the script, some of these variables get set to a different value and I would like to reset them to the values that I had saved.Can you point out a way without using arrays?
I would put the problem code in a subshell instead, to prevent its changes from affecting the rest of the shell.
#!/bin/sh
VAR1=asdf
VAR2=qwertyuipo
(
VAR1=slartibartfast
VAR2=lkjlkdsfh
echo "some stuff"
)
echo "Variables changed inside ( ) do not change outside"
echo "VAR1 is still $VAR1"
Can I do something like this?
temp=`for t in var1 var2 var3; do <save the value> ; done`
<loop which sets the values to a different value>
eval echo $temp
Is there a way I can save the initial values of the variables in a single variable as above(temp)
That would be ugly, glitch-prone, and a gaping security hole(never use eval), which is why I suggested the alternative.
This could work, if your variables don't have more than one line in them.
printf "%s\n" "$var1" "$var2" "$var3" > save
for X in var1 var2 var3
do
read $X
done < save
rm -f save
But again, the best way would be to avoid the problem completely by using a subshell -- that's one reason they exist. Or just don't overwrite those variables in the first place.