Config file auto-updation

Hello All,

I need to update my .cfg file which is used in the script for almost all runs.

myfile.cfg file:

var=1
var1=1
run=0

script:

#! /bin/sh

. /mydir/myfile.cfg

echo $var"\t" $var1

exit

So, the requirement is that the myfile.cfg should update every time I run the script. say run=1 and in the next run run=2 and go on.

I was thinking to do with sed. But it would need a temporary file as my system doesn't support -i.

$ cat myfile.cfg
var=1
var1=1
run=1

$ cat update.sh
num=`grep run= myfile.cfg | sed "s/run=//"`
num=`expr $num + 1`
sed "s/run=.*/run=$num/" myfile.cfg > temp.x
mv temp.x myfile.cfg

$ ./update.sh

$ cat myfile.cfg
var=1
var1=1
run=2

@hanson: Thanks for the concern. But I was thinking to do this without a temporary file.

Space "really" matters on the server that I'm working on :frowning:

$ cat update.sh
num=`grep run= myfile.cfg | sed "s/run=//"`
num=`expr $num + 1`
buffer=`sed "s/run=.*/run=$num/" myfile.cfg`
echo "$buffer" > myfile.cfg

@hanson: Coool... :slight_smile: This works...

awk -F'=' '/run=/ {$NF+=1}{R=(R==""?$0:R RS $0)}END{print R > "myfile.cfg"} ' OFS='=' myfile.cfg

I would advise not to modify your script with every run; it just does not make sense. If you run your scripts in the same session, keep the run No. in a variable; if run across session, keep it in a file, or, e.g. a symbolic link.

I would rather allow only one run. Just by checking with ps -ef or something.. what say???

Which means? One session?

Yes.. Just one session.. :slight_smile:

say the script is running from terminal1 and and it is trying to be started from the another say terminal2, I would not allow that. I would use some thing like

run_count=$(ps -ef | grep myscript | grep -vc grep)
if [ $run_count -gt 1 ]; then
echo "This run is not allowed. Please try after sometime"
exit
else
echo "starting script"
fi

So - if it's one single session, initialize and export a (global) variable, say, RUNNO. from your script, and then, in every new script, add one to it, like (in bash) ((RUNNO++)) . The "locking" that you allude to in your above post can be done with a "lock" file in e.g. /var/run . Just create a file there ( touch /var/run/myscript ) for the duration of your runs, and delete when done. Don't allow any new script if that file exists.