Flav
Posts: 7
Joined: Mon Apr 08, 2013 2:25 pm

Bash script and for loop counter

Thu Jun 20, 2013 7:30 am

Hi there !

Linux noob with Raspbian, I am writing my 1st bash scipt which there is a for loop.
In this loop there is an if condition, if the condition fails, I want to decrement the counter to start again with no impact on the final number of results (hope I am clear enough).
It seems I cannot modify the counter ("let" command doesn't work) and google was not a great help...

Code: Select all

for i in `seq 1 10`		# exact number of increments TBD
do
	# Creates directory to store csv files, its name is date/hour based
	date=`date +%d-%m-%y_%H-%M-%S`
	mkdir $data/$date

	# Executes C program
	sudo ./main

	# Tests if csv files are present
	if [ -e $prog/*.csv ]
	then
		# Moves csv files from C program directory to data base directory
		sudo mv *.csv $data/$date

		# Delay before next C program execution
		sleep 1h		# exact delay TBD
	else
		# If no csv files present, add a message and restart after a small delay
		cp $data/.if_problem $data/$date/READ_ME.txt

		sleep 1
		let "i=i-1"
	fi
done
Does someone as a solution to work with the counter value ?

Thank you
Flav

User avatar
rpdom
Posts: 17275
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: Bash script and for loop counter

Thu Jun 20, 2013 8:20 am

Yes, it won't work like that.

The "seq 1 10" command just returns a value of "1 2 3 4 5 6 7 8 9 10" and the "for" command reads each one of those in turn. seq is only executed once, so they can't change. "let" *does* work, but the for command will just read the next number from the sequence anyway.

Try something like

Code: Select all

i=1
while [ $i -le 10 ]
do
     # Creates directory to store csv files, its name is date/hour based
   date=`date +%d-%m-%y_%H-%M-%S`
   mkdir $data/$date

   # Executes C program
   sudo ./main

   # Tests if csv files are present
   if [ -e $prog/*.csv ]
   then
      # Moves csv files from C program directory to data base directory
      sudo mv *.csv $data/$date

      # Delay before next C program execution
      sleep 1h      # exact delay TBD
      let "i = i + 1"
   else
      # If no csv files present, add a message and restart after a small delay
      cp $data/.if_problem $data/$date/READ_ME.txt

      sleep 1
   fi
done
Note that it *only* increments the counter when a file is found.

Flav
Posts: 7
Joined: Mon Apr 08, 2013 2:25 pm

Re: Bash script and for loop counter

Thu Jun 20, 2013 12:45 pm

rpdom wrote: Note that it *only* increments the counter when a file is found.
This is what I am looking for. I just need to add a kind of security to leave if the system doesn't work for a too long time.

Thank you for your help. ;)

Return to “Beginners”