views:

5905

answers:

3

Hello all,

I wish to introduce a for loop in my shell script and I was hoping I could get some help with this.

I am executing a command from a text file. I wish to execute each command 10 times and insert some stats into a csv file. After that command has been done, I want to start the next BUT put a line break in the CSV file after the first command that was done 10 times.

Is the following correct:

#Function processLine
processLine(){
line="$@"
for i in 1 2 3 4 5 6 7 8 9 10
do
START=$(date +%s.%N)
echo "$line"
eval $line > /dev/null 2>&1

END=$(date +%s.%N)
DIFF=$(echo "$END - $START" | bc)

echo "$line, $START, $END, $DIFF" >> file.csv 2>&1
echo "It took $DIFF seconds"
echo $line
done
}

Thanks all for any help

UPDATE

It is doing the loop correctly, but I can't get it to add a line break after each command is executed 10 times.

A: 

It looks reasonable. Does it do what you want it to?

You could simplify some things, e.g.

DIFF=$(echo "$END - $START" | bc)

could be just

DIFF=$((END - START))

if END and START are integers, and there's no need to put things in variables if you're only going to use them once.

If it's not doing what you want, edit the question to describe the problem (what you see it doing and what you'd rather have it do).

MarkusQ
Note that $END en $START contain reals. This means $(()) won't work, right?
mweerden
@mweerden good catch
MarkusQ
+2  A: 
processLine()
{
    line="$@"

    echo $line >> test_file
    for ((i = 1; i <= 10 ; i++))
    do
        # do not move to the next line
        echo -n "$i," >> test_file
    done

    # move to the next line: add the break
    echo >> test_file
}

echo -n > test_file

processLine 'ls'
processLine 'find . -name "*"'
Mykola Golubyev
A: 

How about just adding a line "echo >> file.csv" after done? Or do you only want an empty line between each block of 10? Then you could do the following:

FIRST=1
processline()
{
  if (( FIRST )) then
    FIRST = 0
  else
    echo >> file.csv
  fi
  ...rest of code...
}

Otherwise you might want to give an example of the desired output and the output you are getting now.

mweerden