- if $log; then
- file=
- if [[ -f $c$((errors-1)) ]]; then
- out="tee -a"
- else
- out=append
- fi
- for ((i=errors; i>=1; i--)); do
- if [[ -f $c$((i-1)) ]]; then
- file=$c$i
- mv $c$((i-1)) $file
- break
- fi
- done
- if [[ ! $file ]]; then
- if [[ -f $c$errors ]]; then
- file=$c$errors
- else
- file=${c}1
- fi
+ done
+ log_name=$1
+ # todo, make option & make them overridable based on command line or env variable
+ [[ -d $cbase ]] || mkdir -p $cbase
+ c=$cbase/$log_name
+ log=false
+ while read -r line; do
+ output+=( "$line" )
+ # If we find something that is not just a newline:
+ if [[ $line ]]; then
+ log=true
+ break
+ fi
+ done
+ glob="$c[0-9]*"
+ # file is error file indicating previous error
+ tmp=($glob); file="${tmp[0]}"
+ if [[ $file == "$glob" ]]; then
+ file=
+ fi
+ if $log; then
+ out=append
+ if [[ $file ]]; then
+ i="${file#$c}"
+ if (( i < errors )); then
+ new_file=$c$((i+1))
+ mvout=$(mv $file $new_file 2>&1) || mverr=$?
+ if (( mverr )); then
+ if [[ $mvout == *": No such file or directory" ]]; then
+ # We've very likely hit a race condition, where another
+ # log-once did the mv before us.
+ return 0
+ else
+ echo "log-once: error on mv $file $new_file"
+ return $mverr
+ fi