Can anyone explain 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 script 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. Feb 25, 2013 at 10:04
-
2Good one. Note that "obsolete" just appears in
help typeset
, not inman typeset
.– fedorquiJul 22, 2014 at 8:05 -
3@ChrisDown, you wouldn't happen to know why, exactly,
typeset
is considered obsolete? Oct 5, 2016 at 2:40 -
2In bash 4.4 and later, it is changed to synonym instead of obsolete.
help typeset
=>A synonym for `declare'. See `help declare'.
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
-
This is a nice comment but how does that answer the question which is about
typeset
anddeclare
?– jw013Feb 25, 2013 at 16:40 -
1This is already well answered by Chris Down, my response is just a case where it's usefull Feb 25, 2013 at 17:31
-
Perhaps I wasn't clear. Comments should be comments, and answers should be answers. This is a comment, not an answer.– jw013Feb 25, 2013 at 20:32
-
9
-
but you still can assign variables with typeset... just replace declare with typeset and you still get the same result. Nov 28, 2017 at 15:14