Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between declare, typeset and local variable in Bash

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.

like image 241
lecodesportif Avatar asked Dec 11 '10 23:12

lecodesportif


People also ask

What does typeset do in bash?

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.

What does typeset mean in shell script?

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.

What is local variable in bash?

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.

Do you need to declare variable in bash?

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.


1 Answers

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

like image 74
Hui Zheng Avatar answered Sep 19 '22 22:09

Hui Zheng