Why does my shell script give the error: "declare: not found"?

declare is a builtin function and it's not available with /bin/sh, only with bash or zsh (and maybe other shells). The syntax may differ from one shell to another. You must choose your sheebang (#!) accordingly: if the script needs to be run by bash, the first line must be

#!/bin/bash

or

#!/usr/bin/env bash

declare is a bash and zsh extension. On your system, /bin/sh is neither bash nor zsh (it's probably ash), so declare isn't available. You can use typeset instead of declare; they're synonyms, but typeset also works in ksh. In ash, there's no equivalent to typeset -i or most other uses of the typeset built-in. You don't actually need typeset -i to declare an integer variable; all it does is allow a few syntactic shortcuts like hello=2+2 for hello=$((2+2)).


declare probably doesn't exist in the shell defined by your shebang - #! /bin/sh.

Try #!/bin/bash instead.

The reason why sourcing it worked is that you were already in a shell that supports declare. Sourcing it didn't open a new shell thus didn't use the shebang that doesn't know declare.