For a code length of 3, the chosen code will rarely contain a digit < 7. For a code length of 4, it will rarely contain a digit < 6; and so on.
Unfortunately I've just noticed a problem myself, please see my third update above. (I've written it after I have read your note, before I've read your update.)
I think that the third attempt also fixes the problems that you describe.
I seem to have payed too little attention to the output, especially for small codes, because the ensuing command prompt always hides the output (because \r sets the cursor to the beginning of the line). Placing an "; echo" after the command in a unix shell helps with this issue.