In bash scripting, what's the different between declare and a normal variable? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election Results Why I closed the “Why is Kali so hard” questionWhat is difference between POSIX, Bash and other shells for scripting?What's the difference between “==” and “=~”?Variable definition in bash using the local keywordIn the Linux Terminal, is there a difference between “bash foo.sh” and “./foo.sh”Difference between writing `function Name …; `, `Name () …; ` and `function Name () …; ` in bashbash vs zsh: scoping and `typeset -g`Combining a variable value and string to form another variableWhat's the different between with a ~ and without a ~ in a string variable in Bash?Temporarily declare a variable in BashThe files with the extension bash and sh
Chebyshev inequality in terms of RMS
Is there hard evidence that the grant peer review system performs significantly better than random?
How does light 'choose' between wave and particle behaviour?
Selecting user stories during sprint planning
Chinese Seal on silk painting - what does it mean?
Are all finite dimensional hilbert spaces isomorphic to spaces with Euclidean norms?
Performance gap between vector<bool> and array
How were pictures turned from film to a big picture in a picture frame before digital scanning?
Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?
How to write the following sign?
Why is it faster to reheat something than it is to cook it?
How do living politicians protect their readily obtainable signatures from misuse?
How to tell that you are a giant?
Did Deadpool rescue all of the X-Force?
Why aren't air breathing engines used as small first stages?
Using et al. for a last / senior author rather than for a first author
Take 2! Is this homebrew Lady of Pain warlock patron balanced?
An adverb for when you're not exaggerating
Why wasn't DOSKEY integrated with COMMAND.COM?
Maximum summed subsequences with non-adjacent items
AppleTVs create a chatty alternate WiFi network
What is the difference between globalisation and imperialism?
What does it mean that physics no longer uses mechanical models to describe phenomena?
What initially awakened the Balrog?
In bash scripting, what's the different between declare and a normal variable?
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Community Moderator Election Results
Why I closed the “Why is Kali so hard” questionWhat is difference between POSIX, Bash and other shells for scripting?What's the difference between “==” and “=~”?Variable definition in bash using the local keywordIn the Linux Terminal, is there a difference between “bash foo.sh” and “./foo.sh”Difference between writing `function Name …; `, `Name () …; ` and `function Name () …; ` in bashbash vs zsh: scoping and `typeset -g`Combining a variable value and string to form another variableWhat's the different between with a ~ and without a ~ in a string variable in Bash?Temporarily declare a variable in BashThe files with the extension bash and sh
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
In bash scripting:
we create variable by just naming it:
abc=ok
or we can use declare
declare abc=ok
what's the difference?
and why does bash make so many ways to create a variable?
bash shell-script variable
add a comment |
In bash scripting:
we create variable by just naming it:
abc=ok
or we can use declare
declare abc=ok
what's the difference?
and why does bash make so many ways to create a variable?
bash shell-script variable
5
When used in a function,declaremakes NAMEs local, as with thelocalcommand. The-goption suppresses this behavior. Seehelp declare.
– Cyrus
Jan 10 '16 at 8:22
2
declaremakes it possible to create associative arrays, integers, and read-only variables. Also, it expands its arguments, so things likedeclare $name=1are possible.
– choroba
Jan 10 '16 at 10:14
add a comment |
In bash scripting:
we create variable by just naming it:
abc=ok
or we can use declare
declare abc=ok
what's the difference?
and why does bash make so many ways to create a variable?
bash shell-script variable
In bash scripting:
we create variable by just naming it:
abc=ok
or we can use declare
declare abc=ok
what's the difference?
and why does bash make so many ways to create a variable?
bash shell-script variable
bash shell-script variable
edited Apr 14 at 11:42
0xc0de
1731110
1731110
asked Jan 10 '16 at 8:19
lovespringlovespring
78611117
78611117
5
When used in a function,declaremakes NAMEs local, as with thelocalcommand. The-goption suppresses this behavior. Seehelp declare.
– Cyrus
Jan 10 '16 at 8:22
2
declaremakes it possible to create associative arrays, integers, and read-only variables. Also, it expands its arguments, so things likedeclare $name=1are possible.
– choroba
Jan 10 '16 at 10:14
add a comment |
5
When used in a function,declaremakes NAMEs local, as with thelocalcommand. The-goption suppresses this behavior. Seehelp declare.
– Cyrus
Jan 10 '16 at 8:22
2
declaremakes it possible to create associative arrays, integers, and read-only variables. Also, it expands its arguments, so things likedeclare $name=1are possible.
– choroba
Jan 10 '16 at 10:14
5
5
When used in a function,
declare makes NAMEs local, as with the local command. The -g option suppresses this behavior. See help declare.– Cyrus
Jan 10 '16 at 8:22
When used in a function,
declare makes NAMEs local, as with the local command. The -g option suppresses this behavior. See help declare.– Cyrus
Jan 10 '16 at 8:22
2
2
declare makes it possible to create associative arrays, integers, and read-only variables. Also, it expands its arguments, so things like declare $name=1 are possible.– choroba
Jan 10 '16 at 10:14
declare makes it possible to create associative arrays, integers, and read-only variables. Also, it expands its arguments, so things like declare $name=1 are possible.– choroba
Jan 10 '16 at 10:14
add a comment |
2 Answers
2
active
oldest
votes
From help -m declare:
NAME
declare- Set variable values and attributes.SYNOPSIS
declare[-aAfFgilnrtux] [-p] [name[=value] ...]DESCRIPTION
Set variable values and attributes.
Declare variables and give them attributes. If no NAMEs are given,
display the attributes and values of all variables.
Options:
-frestrict action or display to function names and definitions
-Frestrict display to function names only (plus line number and
source file when debugging)-gcreate global variables when used in a shell function; otherwise
ignored-pdisplay the attributes and value of each NAME
Options which set attributes:
-ato make NAMEs indexed arrays (if supported)
-Ato make NAMEs associative arrays (if supported)
-ito make NAMEs have the ‘integer’ attribute
-lto convert NAMEs to lower case on assignment
-nmake NAME a reference to the variable named by its value
-rto make NAMEs readonly
-tto make NAMEs have the ‘trace’ attribute
-uto convert NAMEs to upper case on assignment
-xto make NAMEs export
Using ‘
+’ instead of ‘-’ turns off the given attribute.
Variables with the integer attribute have arithmetic evaluation (see
theletcommand) performed when the variable is assigned a value.
When used in a function,
declaremakes NAMEs local, as with thelocal
command. The ‘-g’ option suppresses this behavior.
Exit Status:
Returns success unless an invalid option is supplied or a variable
assignment error occurs.SEE ALSO
bash(1)IMPLEMENTATION
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>
So, 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
yes, the "and attributes" is the point! this is the difference.
– lovespring
Jan 11 '16 at 12:48
Great! I love examples, best way to teach/learn. Thanks!
– turkenh
Aug 4 '17 at 9:02
1
You need to know what "attributes" are to understand this answer. They're properties of the variable like 'integer', 'array', or 'readonly'.
– Noumenon
May 17 '18 at 5:04
add a comment |
abc=ok assigns a value to the variable abc. declare abc declares a variable called abc. The two can be combined as declare abc=ok.
In bash, like other shells, string and array variables don't need to be declared, so declare isn't necessary unless you want to pass options, e.g. declare -A abc to make abc an associative array or declare -r to make a variable read-only. However, inside a function, declare does make a difference: it causes the variable to be local to the function, meaning that the value of the variable outside the function (if any) is preserved. (Unless you use declare -g, which makes the variable not local; this is useful when combined with other options, e.g. declare -gA to create a global associative array in a function.) Example:
f ()
declare a
a='a in f'
b='b in f'
echo "From f: a is $a"
echo "From f: b is $b"
a='Initial a'
b='Initial b'
f
echo "After f: a is $a"
echo "After f: b is $b"
Output:
From f: a is a in f
From f: b is b in f
After f: a is Initial a
After f: b is b in f
Another thing you can do with the declare builtin is
The declare builtin is unique to bash. It's strongly inspired and very close to ksh's typeset builtin, and bash provides typeset as a synonym of declare for compatibility. (I don't know why bash didn't just call it typeset). There's a third synonym, local. There's also export, which is the same as declare -x, again for compatibility (with every Bourne-style shell).
yes! the 'and option' is the point. p.s. if i design the bash, I will let the behavior of "declare" do some thing in different condiftion. this make things simple.
– lovespring
Jan 11 '16 at 12:51
Nice answer. A further question, which one amongstexport,localanddeclareis the most compatible with other shells?
– 0xc0de
Apr 14 at 11:42
1
@0xc0deexportexists in all variants ofsh.localexists only in bash and zsh,declareonly in bash.typesetexists in ksh, bash and zsh.
– Gilles
Apr 14 at 18:58
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "106"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f254367%2fin-bash-scripting-whats-the-different-between-declare-and-a-normal-variable%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
From help -m declare:
NAME
declare- Set variable values and attributes.SYNOPSIS
declare[-aAfFgilnrtux] [-p] [name[=value] ...]DESCRIPTION
Set variable values and attributes.
Declare variables and give them attributes. If no NAMEs are given,
display the attributes and values of all variables.
Options:
-frestrict action or display to function names and definitions
-Frestrict display to function names only (plus line number and
source file when debugging)-gcreate global variables when used in a shell function; otherwise
ignored-pdisplay the attributes and value of each NAME
Options which set attributes:
-ato make NAMEs indexed arrays (if supported)
-Ato make NAMEs associative arrays (if supported)
-ito make NAMEs have the ‘integer’ attribute
-lto convert NAMEs to lower case on assignment
-nmake NAME a reference to the variable named by its value
-rto make NAMEs readonly
-tto make NAMEs have the ‘trace’ attribute
-uto convert NAMEs to upper case on assignment
-xto make NAMEs export
Using ‘
+’ instead of ‘-’ turns off the given attribute.
Variables with the integer attribute have arithmetic evaluation (see
theletcommand) performed when the variable is assigned a value.
When used in a function,
declaremakes NAMEs local, as with thelocal
command. The ‘-g’ option suppresses this behavior.
Exit Status:
Returns success unless an invalid option is supplied or a variable
assignment error occurs.SEE ALSO
bash(1)IMPLEMENTATION
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>
So, 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
yes, the "and attributes" is the point! this is the difference.
– lovespring
Jan 11 '16 at 12:48
Great! I love examples, best way to teach/learn. Thanks!
– turkenh
Aug 4 '17 at 9:02
1
You need to know what "attributes" are to understand this answer. They're properties of the variable like 'integer', 'array', or 'readonly'.
– Noumenon
May 17 '18 at 5:04
add a comment |
From help -m declare:
NAME
declare- Set variable values and attributes.SYNOPSIS
declare[-aAfFgilnrtux] [-p] [name[=value] ...]DESCRIPTION
Set variable values and attributes.
Declare variables and give them attributes. If no NAMEs are given,
display the attributes and values of all variables.
Options:
-frestrict action or display to function names and definitions
-Frestrict display to function names only (plus line number and
source file when debugging)-gcreate global variables when used in a shell function; otherwise
ignored-pdisplay the attributes and value of each NAME
Options which set attributes:
-ato make NAMEs indexed arrays (if supported)
-Ato make NAMEs associative arrays (if supported)
-ito make NAMEs have the ‘integer’ attribute
-lto convert NAMEs to lower case on assignment
-nmake NAME a reference to the variable named by its value
-rto make NAMEs readonly
-tto make NAMEs have the ‘trace’ attribute
-uto convert NAMEs to upper case on assignment
-xto make NAMEs export
Using ‘
+’ instead of ‘-’ turns off the given attribute.
Variables with the integer attribute have arithmetic evaluation (see
theletcommand) performed when the variable is assigned a value.
When used in a function,
declaremakes NAMEs local, as with thelocal
command. The ‘-g’ option suppresses this behavior.
Exit Status:
Returns success unless an invalid option is supplied or a variable
assignment error occurs.SEE ALSO
bash(1)IMPLEMENTATION
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>
So, 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
yes, the "and attributes" is the point! this is the difference.
– lovespring
Jan 11 '16 at 12:48
Great! I love examples, best way to teach/learn. Thanks!
– turkenh
Aug 4 '17 at 9:02
1
You need to know what "attributes" are to understand this answer. They're properties of the variable like 'integer', 'array', or 'readonly'.
– Noumenon
May 17 '18 at 5:04
add a comment |
From help -m declare:
NAME
declare- Set variable values and attributes.SYNOPSIS
declare[-aAfFgilnrtux] [-p] [name[=value] ...]DESCRIPTION
Set variable values and attributes.
Declare variables and give them attributes. If no NAMEs are given,
display the attributes and values of all variables.
Options:
-frestrict action or display to function names and definitions
-Frestrict display to function names only (plus line number and
source file when debugging)-gcreate global variables when used in a shell function; otherwise
ignored-pdisplay the attributes and value of each NAME
Options which set attributes:
-ato make NAMEs indexed arrays (if supported)
-Ato make NAMEs associative arrays (if supported)
-ito make NAMEs have the ‘integer’ attribute
-lto convert NAMEs to lower case on assignment
-nmake NAME a reference to the variable named by its value
-rto make NAMEs readonly
-tto make NAMEs have the ‘trace’ attribute
-uto convert NAMEs to upper case on assignment
-xto make NAMEs export
Using ‘
+’ instead of ‘-’ turns off the given attribute.
Variables with the integer attribute have arithmetic evaluation (see
theletcommand) performed when the variable is assigned a value.
When used in a function,
declaremakes NAMEs local, as with thelocal
command. The ‘-g’ option suppresses this behavior.
Exit Status:
Returns success unless an invalid option is supplied or a variable
assignment error occurs.SEE ALSO
bash(1)IMPLEMENTATION
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>
So, 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
From help -m declare:
NAME
declare- Set variable values and attributes.SYNOPSIS
declare[-aAfFgilnrtux] [-p] [name[=value] ...]DESCRIPTION
Set variable values and attributes.
Declare variables and give them attributes. If no NAMEs are given,
display the attributes and values of all variables.
Options:
-frestrict action or display to function names and definitions
-Frestrict display to function names only (plus line number and
source file when debugging)-gcreate global variables when used in a shell function; otherwise
ignored-pdisplay the attributes and value of each NAME
Options which set attributes:
-ato make NAMEs indexed arrays (if supported)
-Ato make NAMEs associative arrays (if supported)
-ito make NAMEs have the ‘integer’ attribute
-lto convert NAMEs to lower case on assignment
-nmake NAME a reference to the variable named by its value
-rto make NAMEs readonly
-tto make NAMEs have the ‘trace’ attribute
-uto convert NAMEs to upper case on assignment
-xto make NAMEs export
Using ‘
+’ instead of ‘-’ turns off the given attribute.
Variables with the integer attribute have arithmetic evaluation (see
theletcommand) performed when the variable is assigned a value.
When used in a function,
declaremakes NAMEs local, as with thelocal
command. The ‘-g’ option suppresses this behavior.
Exit Status:
Returns success unless an invalid option is supplied or a variable
assignment error occurs.SEE ALSO
bash(1)IMPLEMENTATION
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>
So, 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
edited Oct 29 '18 at 22:49
G-Man
13.8k93870
13.8k93870
answered Jan 10 '16 at 10:17
PandyaPandya
9,1031656107
9,1031656107
yes, the "and attributes" is the point! this is the difference.
– lovespring
Jan 11 '16 at 12:48
Great! I love examples, best way to teach/learn. Thanks!
– turkenh
Aug 4 '17 at 9:02
1
You need to know what "attributes" are to understand this answer. They're properties of the variable like 'integer', 'array', or 'readonly'.
– Noumenon
May 17 '18 at 5:04
add a comment |
yes, the "and attributes" is the point! this is the difference.
– lovespring
Jan 11 '16 at 12:48
Great! I love examples, best way to teach/learn. Thanks!
– turkenh
Aug 4 '17 at 9:02
1
You need to know what "attributes" are to understand this answer. They're properties of the variable like 'integer', 'array', or 'readonly'.
– Noumenon
May 17 '18 at 5:04
yes, the "and attributes" is the point! this is the difference.
– lovespring
Jan 11 '16 at 12:48
yes, the "and attributes" is the point! this is the difference.
– lovespring
Jan 11 '16 at 12:48
Great! I love examples, best way to teach/learn. Thanks!
– turkenh
Aug 4 '17 at 9:02
Great! I love examples, best way to teach/learn. Thanks!
– turkenh
Aug 4 '17 at 9:02
1
1
You need to know what "attributes" are to understand this answer. They're properties of the variable like 'integer', 'array', or 'readonly'.
– Noumenon
May 17 '18 at 5:04
You need to know what "attributes" are to understand this answer. They're properties of the variable like 'integer', 'array', or 'readonly'.
– Noumenon
May 17 '18 at 5:04
add a comment |
abc=ok assigns a value to the variable abc. declare abc declares a variable called abc. The two can be combined as declare abc=ok.
In bash, like other shells, string and array variables don't need to be declared, so declare isn't necessary unless you want to pass options, e.g. declare -A abc to make abc an associative array or declare -r to make a variable read-only. However, inside a function, declare does make a difference: it causes the variable to be local to the function, meaning that the value of the variable outside the function (if any) is preserved. (Unless you use declare -g, which makes the variable not local; this is useful when combined with other options, e.g. declare -gA to create a global associative array in a function.) Example:
f ()
declare a
a='a in f'
b='b in f'
echo "From f: a is $a"
echo "From f: b is $b"
a='Initial a'
b='Initial b'
f
echo "After f: a is $a"
echo "After f: b is $b"
Output:
From f: a is a in f
From f: b is b in f
After f: a is Initial a
After f: b is b in f
Another thing you can do with the declare builtin is
The declare builtin is unique to bash. It's strongly inspired and very close to ksh's typeset builtin, and bash provides typeset as a synonym of declare for compatibility. (I don't know why bash didn't just call it typeset). There's a third synonym, local. There's also export, which is the same as declare -x, again for compatibility (with every Bourne-style shell).
yes! the 'and option' is the point. p.s. if i design the bash, I will let the behavior of "declare" do some thing in different condiftion. this make things simple.
– lovespring
Jan 11 '16 at 12:51
Nice answer. A further question, which one amongstexport,localanddeclareis the most compatible with other shells?
– 0xc0de
Apr 14 at 11:42
1
@0xc0deexportexists in all variants ofsh.localexists only in bash and zsh,declareonly in bash.typesetexists in ksh, bash and zsh.
– Gilles
Apr 14 at 18:58
add a comment |
abc=ok assigns a value to the variable abc. declare abc declares a variable called abc. The two can be combined as declare abc=ok.
In bash, like other shells, string and array variables don't need to be declared, so declare isn't necessary unless you want to pass options, e.g. declare -A abc to make abc an associative array or declare -r to make a variable read-only. However, inside a function, declare does make a difference: it causes the variable to be local to the function, meaning that the value of the variable outside the function (if any) is preserved. (Unless you use declare -g, which makes the variable not local; this is useful when combined with other options, e.g. declare -gA to create a global associative array in a function.) Example:
f ()
declare a
a='a in f'
b='b in f'
echo "From f: a is $a"
echo "From f: b is $b"
a='Initial a'
b='Initial b'
f
echo "After f: a is $a"
echo "After f: b is $b"
Output:
From f: a is a in f
From f: b is b in f
After f: a is Initial a
After f: b is b in f
Another thing you can do with the declare builtin is
The declare builtin is unique to bash. It's strongly inspired and very close to ksh's typeset builtin, and bash provides typeset as a synonym of declare for compatibility. (I don't know why bash didn't just call it typeset). There's a third synonym, local. There's also export, which is the same as declare -x, again for compatibility (with every Bourne-style shell).
yes! the 'and option' is the point. p.s. if i design the bash, I will let the behavior of "declare" do some thing in different condiftion. this make things simple.
– lovespring
Jan 11 '16 at 12:51
Nice answer. A further question, which one amongstexport,localanddeclareis the most compatible with other shells?
– 0xc0de
Apr 14 at 11:42
1
@0xc0deexportexists in all variants ofsh.localexists only in bash and zsh,declareonly in bash.typesetexists in ksh, bash and zsh.
– Gilles
Apr 14 at 18:58
add a comment |
abc=ok assigns a value to the variable abc. declare abc declares a variable called abc. The two can be combined as declare abc=ok.
In bash, like other shells, string and array variables don't need to be declared, so declare isn't necessary unless you want to pass options, e.g. declare -A abc to make abc an associative array or declare -r to make a variable read-only. However, inside a function, declare does make a difference: it causes the variable to be local to the function, meaning that the value of the variable outside the function (if any) is preserved. (Unless you use declare -g, which makes the variable not local; this is useful when combined with other options, e.g. declare -gA to create a global associative array in a function.) Example:
f ()
declare a
a='a in f'
b='b in f'
echo "From f: a is $a"
echo "From f: b is $b"
a='Initial a'
b='Initial b'
f
echo "After f: a is $a"
echo "After f: b is $b"
Output:
From f: a is a in f
From f: b is b in f
After f: a is Initial a
After f: b is b in f
Another thing you can do with the declare builtin is
The declare builtin is unique to bash. It's strongly inspired and very close to ksh's typeset builtin, and bash provides typeset as a synonym of declare for compatibility. (I don't know why bash didn't just call it typeset). There's a third synonym, local. There's also export, which is the same as declare -x, again for compatibility (with every Bourne-style shell).
abc=ok assigns a value to the variable abc. declare abc declares a variable called abc. The two can be combined as declare abc=ok.
In bash, like other shells, string and array variables don't need to be declared, so declare isn't necessary unless you want to pass options, e.g. declare -A abc to make abc an associative array or declare -r to make a variable read-only. However, inside a function, declare does make a difference: it causes the variable to be local to the function, meaning that the value of the variable outside the function (if any) is preserved. (Unless you use declare -g, which makes the variable not local; this is useful when combined with other options, e.g. declare -gA to create a global associative array in a function.) Example:
f ()
declare a
a='a in f'
b='b in f'
echo "From f: a is $a"
echo "From f: b is $b"
a='Initial a'
b='Initial b'
f
echo "After f: a is $a"
echo "After f: b is $b"
Output:
From f: a is a in f
From f: b is b in f
After f: a is Initial a
After f: b is b in f
Another thing you can do with the declare builtin is
The declare builtin is unique to bash. It's strongly inspired and very close to ksh's typeset builtin, and bash provides typeset as a synonym of declare for compatibility. (I don't know why bash didn't just call it typeset). There's a third synonym, local. There's also export, which is the same as declare -x, again for compatibility (with every Bourne-style shell).
answered Jan 11 '16 at 1:21
GillesGilles
548k13011151631
548k13011151631
yes! the 'and option' is the point. p.s. if i design the bash, I will let the behavior of "declare" do some thing in different condiftion. this make things simple.
– lovespring
Jan 11 '16 at 12:51
Nice answer. A further question, which one amongstexport,localanddeclareis the most compatible with other shells?
– 0xc0de
Apr 14 at 11:42
1
@0xc0deexportexists in all variants ofsh.localexists only in bash and zsh,declareonly in bash.typesetexists in ksh, bash and zsh.
– Gilles
Apr 14 at 18:58
add a comment |
yes! the 'and option' is the point. p.s. if i design the bash, I will let the behavior of "declare" do some thing in different condiftion. this make things simple.
– lovespring
Jan 11 '16 at 12:51
Nice answer. A further question, which one amongstexport,localanddeclareis the most compatible with other shells?
– 0xc0de
Apr 14 at 11:42
1
@0xc0deexportexists in all variants ofsh.localexists only in bash and zsh,declareonly in bash.typesetexists in ksh, bash and zsh.
– Gilles
Apr 14 at 18:58
yes! the 'and option' is the point. p.s. if i design the bash, I will let the behavior of "declare" do some thing in different condiftion. this make things simple.
– lovespring
Jan 11 '16 at 12:51
yes! the 'and option' is the point. p.s. if i design the bash, I will let the behavior of "declare" do some thing in different condiftion. this make things simple.
– lovespring
Jan 11 '16 at 12:51
Nice answer. A further question, which one amongst
export, local and declare is the most compatible with other shells?– 0xc0de
Apr 14 at 11:42
Nice answer. A further question, which one amongst
export, local and declare is the most compatible with other shells?– 0xc0de
Apr 14 at 11:42
1
1
@0xc0de
export exists in all variants of sh. local exists only in bash and zsh, declare only in bash. typeset exists in ksh, bash and zsh.– Gilles
Apr 14 at 18:58
@0xc0de
export exists in all variants of sh. local exists only in bash and zsh, declare only in bash. typeset exists in ksh, bash and zsh.– Gilles
Apr 14 at 18:58
add a comment |
Thanks for contributing an answer to Unix & Linux Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f254367%2fin-bash-scripting-whats-the-different-between-declare-and-a-normal-variable%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
5
When used in a function,
declaremakes NAMEs local, as with thelocalcommand. The-goption suppresses this behavior. Seehelp declare.– Cyrus
Jan 10 '16 at 8:22
2
declaremakes it possible to create associative arrays, integers, and read-only variables. Also, it expands its arguments, so things likedeclare $name=1are possible.– choroba
Jan 10 '16 at 10:14