good
- Putting this in a function will definitely make it more reusable.
- It was nice that it keeps the time output on one line.
- Your indentation is consistent which makes reading everything quite easy.
- The usability of your timer is very friendly and the
help
docs are thorough. I like the flexibility of your inputs.
suggestions
- It would be nice to include some examples of usage. The
help
section suffices in this case, but in code this long it is a bit buried. - I generally find the advice of https://www.shellcheck.net/ to be quite helpful. The next few points will cover things uncovered by that tool.
- The
let
form of telling the shell to do math will work, but it has lost favor to the(( ))
form of doing math. One advantage of the(( ))
for doing math on a line by itself is that it becomes natural to use the$(( ))
for doing calculations in a substitution. As SC2219 notes(( ))
also doesn't have the quoting hazards thatlet
does. - It is a good habit to pass your function arguments with substitutions as double quoted. This will prevent the shell from splitting something into two arguments because of internal spaces when you are expecting only one. See SC2086 for more on this.
- Another advantage of
let
or(( ))
is that variables are available without using the$
in front of them. See also SC2004. - It'd be nice if it didn't print the hours or minutes when they're zero. All of my tests were shorter than that so they were always zero.
- I really wished that it let me do a countdown, but I understand that could be a feature you have no interest in.
- Shells are often rather imprecise when it comes to
sleep
ing how much you want. Even if thesleep 1
was for precisely one second the rest of your code is going to consume some amount of CPU time and so this will add a bit of time to each iteration. Trying to fix this in a shell script is probably not worth it, but it could be a fun challenge. - You mix
[[ ]]
and[ ]
for conditionals. The[[ ]]
version is more modern and has fewer surprises. - I thought it was neat to have nested functions, but it turns out "Bash has local variables, but not local functions." (from this discusison) When I sourced the file with your timer code in it and looked at
set
I found that all of the functions were fully visible. Since you're not actually hiding anything it'd be better to move those functions above timer so they're clearly not "trying to hide".
Really these are all pretty minor issues. They're some good things to think about if you're doing further shell scripts, but the existing code is pretty good already. The readability of the code is quite good and it isn't hard to guess that you've had good experience in some more normal procedural language or a few.
If you choose to revise this script, remember it should be posted as a new question on this site rather than editing this question.