Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Here is a simple example showing that using declare in a script the script will not run, while sourcing the script will:

$ cat /tmp/new
#! /bin/sh
declare -i  hello
$ chmod a+rwx /tmp/new
$ /tmp/new
/tmp/new: 3: declare: not found
$ source /tmp/new
$ 

I wonder why directly running the script doesn't work, while sourcing it does? How can I make the first one work? Thanks!

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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.

share|improve this answer
add comment

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)).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.