The file has Windows line endings
CommonEdited or checked out on Windows; bash sees do\r, then\r, fi\r as unknown words.
Confirm
cat -v script.sh | head -3
^M at the end of lines
Fix
- Strip the carriage returns: sed -i 's/\r$//' script.sh (or dos2unix script.sh).
- Stop them coming back: add *.sh text eol=lf to .gitattributes.
sed -i 's/\r$//' script.sh
Reproduced on Ubuntu 24.04: the same loop then ran.