while loop - Format increment variable output in bash -
i'm stuck on rather simple problem increment of variable gets printed out consecutive strings file.
here's sample of code:
#!/usr/bin/bash _sest=`date +%y\/%m\/%d\ %h\-%m\-%s` n="0" execution_it(){ while read $3 ((n++)) printf $n done < execlog.txt } echo "test" && echo $_sest printf "execution $(execution_it) started $_sest\r\n" >> execlog.txt
the problem output gets formatted this:
execution started 2016/02/08 19-06-44 execution 1 started 2016/02/08 19-06-44 execution 12 started 2016/02/08 19-06-44 execution 123 started 2016/02/08 19-06-45 execution 1234 started 2016/02/08 19-06-45 execution 12345 started 2016/02/08 19-06-45 execution 123456 started 2016/02/08 19-06-46...
... instead of:
execution 1 started 2016/02/08 19-06-44 execution 2 started 2016/02/08 19-06-44 execution 3 started 2016/02/08 19-06-45...
this working version got after trying cut -d
; awk
; sed
; , c-like syntax for
loop. there version similar while read line
, output same. suggestions well-appreciated.
as understand it, printing one line file "execlog.txt", , specifically, 1 last line appended.
all line contains count of lines in file , date.
done better this:
_logfile="execlog.txt" n="$(wc -l <"$_logfile")" ### count number of lines in log file. _sest="$(date +%y\/%m\/%d\ %h\-%m\-%s)" ### time before used. echo "test $_sest $_logfile" printf "execution %s started %s\r\n" "$n" "$_sest" | tee -a "$_logfile"
if must have loop each line else, understand variable n not lose value on exiting function. so, used later in script.
print in line added logfile:
#!/usr/bin/bash _logfile="execlog.txt" execution_it(){ n="0" while ifs= read -r line echo "loop $n" ((n++)) # $line. done < "$_logfile" } execution_it ### execute loop. _sest="$(date +%y\/%m\/%d\ %h\-%m\-%s)" ### time before used. echo "test time=$_sest , count=$n" printf "execution %s started %s\r\n" "$n" "$_sest" >> "$_logfile"
understand simple example not have control on race conditions. other script may write line logfile between script has counted lines , before appended line added. in case, count wrong. or several copies of script running have same (incorrect) count.
Comments
Post a Comment