Can anyone explain the difference between declare and typeset with real-life examples?
2 Answers
In bash, typeset and declare are exactly the same. The only difference is that typeset is considered obsolete.
typeset: typeset [-aAfFgilrtux] [-p] name[=value] ...
Set variable values and attributes.
Obsolete. See `help declare'.
The man page even lists them in the same breath:
declare [-aAfFgilrtux] [-p] [name[=value] ...]
typeset [-aAfFgilrtux] [-p] [name[=value] ...]
Declare variables and/or give them attributes.
typeset is portable to some other shells, for example, ksh93. If you are aiming for cross-shell portability, use typeset (and make sure that the way you are calling it is portable). If you don't care about such portability, use declare.
-
can you please provide some example of where and why this use in bash scriptRahul Patil– Rahul Patil2013-02-25 08:54:49 +00:00Commented Feb 25, 2013 at 8:54
-
1...like I said, they are exactly the same. I don't understand how I can differentiate them if they are so.Chris Down– Chris Down2013-02-25 10:04:46 +00:00Commented Feb 25, 2013 at 10:04
-
2Good one. Note that "obsolete" just appears in
help typeset, not inman typeset.fedorqui– fedorqui2014-07-22 08:05:40 +00:00Commented Jul 22, 2014 at 8:05 -
3@ChrisDown, you wouldn't happen to know why, exactly,
typesetis considered obsolete?Alexej Magura– Alexej Magura2016-10-05 02:40:34 +00:00Commented Oct 5, 2016 at 2:40 -
4In bash 4.4 and later, it is changed to synonym instead of obsolete.
help typeset=>A synonym for `declare'. See `help declare'.Koichi Nakashima– Koichi Nakashima2021-08-20 11:14:08 +00:00Commented Aug 20, 2021 at 11:14
I know a case where declare is useful to avoid the evil eval : variable indirection :
$ var=foo
$ x=var
$ declare "$x=another_value"
$ echo $var
another_value
-
2This is a nice comment but how does that answer the question which is about
typesetanddeclare?jw013– jw0132013-02-25 16:40:05 +00:00Commented Feb 25, 2013 at 16:40 -
1This is already well answered by Chris Down, my response is just a case where it's usefullGilles Quénot– Gilles Quénot2013-02-25 17:31:47 +00:00Commented Feb 25, 2013 at 17:31
-
1Perhaps I wasn't clear. Comments should be comments, and answers should be answers. This is a comment, not an answer.jw013– jw0132013-02-25 20:32:01 +00:00Commented Feb 25, 2013 at 20:32
-
9My snippet wouldn't clear in a commentGilles Quénot– Gilles Quénot2013-02-25 21:52:17 +00:00Commented Feb 25, 2013 at 21:52
-
but you still can assign variables with typeset... just replace declare with typeset and you still get the same result.pcarvalho– pcarvalho2017-11-28 15:14:02 +00:00Commented Nov 28, 2017 at 15:14