37

Can anyone explain difference between declare and typeset with real life examples .

2 Answers 2

38

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.

5
  • 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.
    – Chris Down
    Feb 25, 2013 at 10:04
  • 2
    Good one. Note that "obsolete" just appears in help typeset, not in man typeset.
    – fedorqui
    Jul 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
  • 2
    In 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
5

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
5
  • This is a nice comment but how does that answer the question which is about typeset and declare?
    – jw013
    Feb 25, 2013 at 16:40
  • 1
    This 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.
    – jw013
    Feb 25, 2013 at 20:32
  • 9
    My snippet wouldn't clear in a comment 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
    Nov 28, 2017 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.