0

I have a simple bash function to increment a number and store it in a file:

get_next_int (){
   my_file="$HOME/next_int.json"
   touch "$my_file"
   typeset -i my_num=$(cat "$my_file")
   echo "$((++my_num))" > "$my_file" | tee
}

regarding this line:

echo "$((++my_num))" > "$my_file" | tee

out of curiousity, is there a way to overwrite the file with the incremented integer and echo it to stdout?

this answer about tee doesn't seem to cover my case.

How to redirect output to a file and stdout | Stack Overflow

also, as an aside, regarding this line:

typeset -i my_num=$(cat "$my_file")

that will grab the integer representation of the string from the file. However if the file is empty, I need to default to 1.

Is there a way to do something like:

typeset -i my_num=$(cat "$my_file" | default "1")
3
echo "$(( ++my_num ))" | tee "$my_file"

Tee writes te the named file(s) and to standard output by default.

After typeset -i my_num=$(cat "$my_file") (which could be typeset -i my_num=$(<"$my_file") in bash), you could use

my_num=$(( my_num == 0 ? 1 : my_num ))

to set it to 1 if it's value is zero. Integer variables in bash evaluate to zero if empty.

I was going to suggest my_num=${my_num:-1} but since my_num is an integer variable, it will expand to zero if it's empty, not to the empty string, which means that the ${variable:-value} parameter substitution would not work (this would otherwise expand to value if the variable was unset or empty).


I would probably have written the function as

get_next_int () {
    local -i val
    read val <"$HOME/next_int.json"
    val=$(( val == 0 ? 1 : val ))
    printf "%d\n" "$(( val + 1 ))" | tee "$HOME/next_int.json"
}

assuming "$HOME/next_int.json" always contained a single integer. I've left out the touch because the files modification timestamp would be updated by tee (keep touch if you need the access timestamp updated as well).

  • does that overwrite the file? – Alexander Mills Apr 11 '18 at 18:41
  • I assume so, and thank you, also if you have thoughts about the aside question, that helps – Alexander Mills Apr 11 '18 at 18:42
  • 1
    @AlexanderMills It does, unless tee -a is used for appending. – Kusalananda Apr 11 '18 at 18:42
  • got it, any idea how to use a default string if cat comes up with empty stdout? – Alexander Mills Apr 11 '18 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.