HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashMinor

Counting seconds until auto-log-off

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
countinguntillogautosecondsoff

Problem

I've just created a teeny little script to count the seconds until I get auto-logged off. I already solved my issue with my ssh client settings, but I'd still like any help making the bash script nicer to read, or just tips in general.

#!/bin/bash

count=0
while ( [ : ] )
do
  count=$(($count+1))
  n=${n:-0}
  for i in `seq 0 $n`; do echo -en '\b'; done
  n="${#count}"
  echo -n $count
  sleep 1
done

Solution

count=0
while true; do
  printf "\r%d" $((++count))
  sleep 1
done


Your while condition is doing a lot of work just to return true: you launch a subshell, and evaluate a test giving a 1-character string (which will always return true). Make it simpler and more readable by just executing the true program.

Note that variable names inside an arithmetic expression do not require the leading dollar sign in most cases. That's quietly documented here:


"Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax."

printf is more portable than echo, if that's a concern for you. I also find it makes your intentions more obvious.

Instead of backing up the right number of characters, just carriage return to the first column and overwrite the previous contents.

Code Snippets

count=0
while true; do
  printf "\r%d" $((++count))
  sleep 1
done

Context

StackExchange Code Review Q#20418, answer score: 5

Revisions (0)

No revisions yet.