Differences between declare, typeset and local variable in Bash

BashShellVariablesScopeDeclare

Bash Problem Overview


When typing variables in Bash, what is the difference between declare and typeset? When used inside a function: what is the difference between declare and typeset and local?

The only difference I have come across is that typeset is portable to ksh scripts. Other than that, are there any reasons why one should be preferred over the other?

UPDATE: Added local to the question.

Bash Solutions


Solution 1 - Bash

  • Difference between typeset and declare:

The former is more portable(e.g. ksh), while the latter is more preferable when portability is not a concern.

  • Difference between declare(or typeset) and local when used inside a function:

The former implies the latter, but more powerful. For example, declare -i x makes x have the integer attribute, declare -r x makes x readonly, etc.

Solution 2 - Bash

As far as bash is concerned, no, there is no difference. In fact, the manpage has them share the same definition

> declare [-aAfFilrtux] [-p] > [name[=value] ...]
typeset > [-aAfFilrtux] [-p] [name[=value] > ...]
Declare variables and/or > give them attributes. If no names are > given then display the values of > variables. The -p option will display > the attributes and values of each > name...

I also found this little tidbit which further substantiates my claim as well as the ksh portability you mentioned.

> The declare or typeset builtins, > which are exact synonyms, permit modifying the properties of variables. > This is a very weak form of the typing > [1] available in certain programming > languages. The declare command is > specific to version 2 or later of > Bash. The typeset command also works > in ksh scripts.

Solution 3 - Bash

In the Bash manual under section 4.2 Bash Builtin Commands it states:

>'typeset'
typeset [-afFrxi] [-p] [NAME[=VALUE] ...]
The 'typeset' command is supplied for compatibility with the Korn shell; however, it has been deprecated in favor of the 'declare' builtin command.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlecodesportifView Question on Stackoverflow
Solution 1 - BashHui ZhengView Answer on Stackoverflow
Solution 2 - BashSiegeXView Answer on Stackoverflow
Solution 3 - BashDennis WilliamsonView Answer on Stackoverflow