|
|||||||
| Forums | Search Forums | Register | Forum Rules | Man Pages | Albums | FAQ | Members | Calendar | Search | Today's Posts | Mark Forums Read |
| Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts and shell scripting languages here. |
|
|
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Preserving values with for loop for later use
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? |
| Sponsored Links | ||
|
|
#2
|
|||
|
|||
|
I would put the problem code in a subshell instead, to prevent its changes from affecting the rest of the shell. Code:
#!/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" |
| Sponsored Links | ||
|
|
#3
|
|||
|
|||
|
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) |
|
#4
|
|||
|
|||
|
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. Code:
printf "%s\n" "$var1" "$var2" "$var3" > save
for X in var1 var2 var3
do
read $X
done < save
rm -f saveBut 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. |
| Sponsored Links | ||
|
![]() |
| Thread Tools | Search this Thread |
| Display Modes | |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Array Variable being Assigned Values in Loop, But Gone when Loop Completes??? | mrm5102 | Shell Programming and Scripting | 5 | 10-19-2012 10:00 AM |
| Preserving whitespace in a for loop | s_becker | Shell Programming and Scripting | 7 | 03-26-2009 03:09 PM |
| adding values with a loop | hcclnoodles | Shell Programming and Scripting | 1 | 05-27-2008 06:42 AM |
| getting values from variable in a loop | kriuz | Shell Programming and Scripting | 3 | 01-22-2008 04:50 PM |
| while read loop preserving leading whitespace | zazzybob | Shell Programming and Scripting | 3 | 06-07-2004 05:36 PM |
|
|