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.
typeset sets attributes and values for shell variables and functions. When typeset is invoked inside a function, a new instance of the variables name is created. The variables value and type are restored when the function completes.
typeset is a built-in shell command as well as a separate utility. An autoloaded function is defined (loaded) by the /bin/sh shell when invoked as a command name, it's not already defined to the shell, and the function definition file is found in a directory specified in the FPATH variable.
A variable declared as local is one that is visible only within the block of code in which it appears. It has local "scope". In a function, a local variable has meaning only within that function block.
A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.
typeset
and declare
:The former is more portable(e.g. ksh), while the latter is more preferable when portability is not a concern.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With