Manipulating variables in shell script

Hello,
I know this should be simple but cant find a solution yet.I have the following in a sh script called "var"

#!/bin/bash
var1=0

And on another script called "main" I use a if construct:

#!/bin/bash
. var
if [ "$var1" == "0" ]
then
Do this
else
do that
fi

Now in "do this" part,I have to change the value of var1 from "0" to "1".Any help is much appreciated :).Thanks
Regards,
vijai

I am not sure whether I got your question correctly.

To change it to 1, simply assign it:

var1=1

But, keep in mind, this does not change the value in the "var" file. To change in the "var" file,

sed -i 's/\(var1=\).*/\11/'  var

Guru.

Thanks for your answer :slight_smile:
Actually I need to have a counter like variable.I have a variable "var1" in one .sh and use it in another .sh in "if" statement.

!#/bin/bash
if [ "$var1" == "0" ]
then
#Do a command here
#and change the value of var1 from 0 to 1 here permanently so that next time the sh is executed,it reads 1.
fi

I tried the second command which you gave but it doesnt work for me :(.No error but doesn't work.

The sed command provided updates your "var" file with the value 1. This command does not give any output. You will see the changes next time when you source your file.

Guru.

Thank you :slight_smile:
There was a typo in my file.Works wonders now :slight_smile:

---------- Post updated at 04:17 PM ---------- Previous update was at 03:38 PM ----------

could you explain that line so that I can learn it?Also could I make changes to two variables within the same line given that both the variables is going to attain the same value?If yes could you show an example?Thanks a ton :)And sorry for my numerous silly questions :o.

Here's a simpler version that should be clear. "Change var1= line to var1=1":

sed -i 's/var1=.*/var1=1/' var

Yes, you could easily change two variables, if I get your meaning:

sed -i -e 's/var1=.*/var1=1/' -e 's/var2=.*/var2=1/' var
sed -i 's/\(var1=\).*/\11/'  var 

-i To update the file in-place
s - To find and replace (eg: s/find/replace/)
var1= - Finds the line containing the pattern var1= and it is grouped using brackets () which can be accessed in the replacement section as \1
\11 - \1 is stands for "var1=" in this case and the second 1 is the replacement value.

To do it for multiple variables, do something like:

sed -i 's/\(var1=\).*/\11/; s/\(var2=\).*/\15/' file

where the value of var1 is set to 1 and var2 is set to 5.

Guru.

Thank you!was really helpful :smiley:

.....