The question is published on by Tutorial Guruji team.
In bash scripting:
we create variable by just naming it:
or we can use
what’s the difference?
and why does bash make so many ways to create a variable?
help -m declare:
declare– Set variable values and attributes.
Set variable values and attributes.
Declare variables and give them attributes. If no NAMEs are given, display the attributes and values of all variables.
restrict action or display to function names and definitions
restrict display to function names only (plus line number and source file when debugging)
create global variables when used in a shell function; otherwise ignored
display the attributes and value of each NAME
Options which set attributes:
to make NAMEs indexed arrays (if supported)
to make NAMEs associative arrays (if supported)
to make NAMEs have the ‘integer’ attribute
to convert NAMEs to lower case on assignment
make NAME a reference to the variable named by its value
to make NAMEs readonly
to make NAMEs have the ‘trace’ attribute
to convert NAMEs to upper case on assignment
to make NAMEs export
+’ instead of ‘
-’ turns off the given attribute.
Variables with the integer attribute have arithmetic evaluation (see the
letcommand) performed when the variable is assigned a value.
When used in a function,
declaremakes NAMEs local, as with the
localcommand. The ‘
-g’ option suppresses this behavior.
Returns success unless an invalid option is supplied or a variable assignment error occurs.
GNU bash, version 4.3.11(1)-release (i686-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
declare is used for setting variable values and attributes.
Let me show the use of two attributes with a very simple example:
$ # First Example: $ declare -r abc=ok $ echo $abc ok $ abc=not-ok bash: abc: readonly variable $ # Second Example: $ declare -i x=10 $ echo $x 10 $ x=ok $ echo $x 0 $ x=15 $ echo $x 15 $ x=15+5 $ echo $x 20
From the above example, I think you should understand the usage of
declare variable over normal variable! This type of
declareation is useful in functions, loops with scripting.
Also visit Typing variables: declare or typeset