Created
October 23, 2016 15:01
-
-
Save binand/7b7f0a89f1c068259f61b31d94fe9f89 to your computer and use it in GitHub Desktop.
Revisions
-
binand created this gist
Oct 23, 2016 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,55 @@ #!/bin/bash # Initializes the counter to 0 (uses filename in arg #1 for state). Returns 0 on success. function init_counter() { local _f=$1 if [ ! -f $_f ]; then local _t=$( mktemp $( dirname $_f )/b.XXXXXXXX ) echo 0 > $_t mv -f $_t $_f fi export COUNTER_FILE=$_f return 0 } # Get the counter's value. Returns value. function get_counter() { local _f=$COUNTER_FILE local _v= if [ -z "$_f" -o \! -f "$_f" ]; then return $(( 2 ** 31 )) fi _v=$( < $_f ) echo $_v return $_v } # Set the counter's value to arg #1. Returns new value. function set_counter() { local _f=$COUNTER_FILE local _new=$1 if [ -z "$_f" -o \! -f "$_f" ]; then return $(( 2 ** 31 )) fi local _t=$( mktemp $( dirname $_f )/b.XXXXXXXX ) echo $_new > $_t mv -f $_t $_f echo $_new return $_new } # Increment the counter's value by arg #1. Returns new value. function inc_counter() { local _inc=$1 local _cur=$( get_counter ) local _r=$( set_counter $(( $_cur + $_inc )) ) echo $_r return $_r } # Add 1 to the counter's value. Returns new value. function add_counter() { local _r=$( inc_counter 1 ) echo $_r return $_r }