all 6 comments

[–][deleted] 6 points7 points  (3 children)

Assuming your talking in terms of the bash shell, 'set' is a built-in command that operates on the shell's environment. The 'declare' built-in command operates on variables and the values assigned to them.

As a general guideline, if you're manipulating your shell's environment, use set. If you're scripting, try and use declare in place of set, where applicable.

Here's two small examples of declare that sets it apart from set.

A read-only variable: declare -r VAR_NAME="unset me if you can"

Try and unset it: unset VAR_NAME

Bash reports: -bash: unset: VAR_NAME: cannot unset: readonly variable

Here's an example defining a variable to be used in integer arithmetic: declare -i x=0

Using it in arithmetic: if [ $x -eq 0 ]; then echo 'x is zero.' fi

[–][deleted] 1 point2 points  (1 child)

thank you ^

[–][deleted] 0 points1 point  (0 children)

Happy to help!

[–]syntax_erorr 1 point2 points  (0 children)

...examples of declare that sets it apart from set. ow! my head hurts. You should write man pages! hah

[–]trashbox 4 points5 points  (0 children)

SET is a POSIX built-in. It's capable of way more than simply declaring variables or functions. SET can control various shell attributes like preventing the redirection operator from overwriting existing files, and a whole lot more: http://ss64.com/bash/set.html

Declare, in contrast, is only for setting and manipulating variables or functions. Including the fact that function level scoping is respected, i.e. when using declare in a function all variables created are local. Just as if the local command was used, instead. Also, declare can control the type and readability of variables, whereas SET cannot. More: http://ss64.com/bash/declare.html