Ben's Blog

I.T., unix / linux ben July 26, 2011

Shell scripting – updating a file holding a counter

[bash]counter=`cat /tmp/counter` ; echo "$counter+1" | bc > /tmp/counter[/bash]

note that loading the /tmp/counter into the variable is a necessary indirection, the following:

[bash]echo "`cat /tmp/counter`+1" | bc > /tmp/counter[/bash]

would not work as the output redirection gets triggered before the cat gets a chance to happen, so the file is emptied too early.

Recent Comments

  1. thomas says:
    February 4, 2013 at 9:07 am

    # echo 2 > /tmp/counter
    # echo $(($(cat /tmp/counter)+3))

    Reply
    • Ben says:
      February 4, 2013 at 11:13 am

      I’m pretty unclear with what’s going on exactly there, care to explain?

      Reply
  2. PL says:
    June 10, 2013 at 9:34 am

    Since we’re dealing with integers, I would rather write:
    f=/tmp/counter; n=`cat $f | xargs expr 1 +`; echo $n > $f

    No need for bc this way. But you still need a variable though :/

    ps: thx for this blog, some articles really helped me

    Reply
    • Ben says:
      June 10, 2013 at 7:44 pm

      It’s true bc is not always there to help. Thanks for your contribution & dropping a “thx”!

      Reply

Leave a Comment

Cancel reply

This blog is solar powered

Interactive

Handwriting Capture
Mandalagaba
IPv6 link-local to MAC converter
IPv6 MAC to link-local converter
Markov Text Generation
Markov Word Generation
Markov Music Generation
Duplogrifier
Flood Fill Algorithms
Homestead Metrics
RGB Playground
Web Games

Categories

  • aesthetics111
    • plots54
    • specular holography6
  • Books3
  • I.T.202
    • 3D modeling / printing21
    • AI6
    • all out geekery36
    • electronics27
    • homestead automation6
    • maniacal paranoia25
    • plotters49
    • unix / linux29
    • video games4
    • web development29
    • web games3
  • Lego / Duplo67
  • life in the U.S.42
  • miscellaneous202
  • nature encounters114
  • old vinyls3
  • organs2
  • self sustainability560
    • agriculture105
    • apiculture38
    • apple20
    • building131
    • canning3
    • crochet6
    • foraging6
    • hunting10
    • maple syrup47
    • poultry39
    • preserving2
    • solar power28
    • water23
    • wood84
  • trip to a new life6
Theme by Bloompixel. Proudly Powered by WordPress