The Bash declare Statement
Although rarely used, the bash declare statement does have a couple useful options. It can mark a variable as read only and also mark it as being a number only.
To declare a variable as read only, use the following statement:
declare -r varname
Consider the following script:
#!/bin/bash
a=13
declare -r a
echo $a
a=14
echo $a
When run, the second assignment will fail:
$ sh decl.sh 13 decl.sh: line 6: a: readonly variable
To declare that a variable should accept only numeric values (integers), use the following statement:
declare -i varname
Consider the following script:
#!/bin/bash
declare -i a
a=12
echo $a
a=hello
echo $a
When run, the second assignment will assign zero to the variable rather than the string "hello" that appears in the statement:
$ sh decl2.sh 12 0
The declare statment has other options; the -a option can be used to declare a variable as an array, but it's not necessary. All variables can be used as arrays without explicit definition. As a matter of fact, it appears that in a sense, all variables are arrays, and that assignment without a subscript is the same as assigning to "[0]". Consider the following script:
#!/bin/bash
a=12
echo ${a[0]}
b[0]=13
echo $b
When run it produces:
$ sh arr.sh 12 13
For further options, see the bash man page (search for "^SHELL BUILTINS", then search for "declare").
Mitch Frazier is an Associate Editor for Linux Journal.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Validate an E-Mail Address with PHP, the Right Way
- A Topic for Discussion - Open Source Feature-Richness?
- Download the Free Red Hat White Paper "Using an Open Source Framework to Catch the Bad Guy"
- The Secret Password Is...
- New Products
- myip
3 hours 24 min ago - Keeping track of IP address
5 hours 15 min ago - Roll your own dynamic dns
10 hours 28 min ago - Please correct the URL for Salt Stack's web site
13 hours 40 min ago - Android is Linux -- why no better inter-operation
15 hours 55 min ago - Connecting Android device to desktop Linux via USB
16 hours 23 min ago - Find new cell phone and tablet pc
17 hours 22 min ago - Epistle
18 hours 50 min ago - Automatically updating Guest Additions
19 hours 59 min ago - I like your topic on android
20 hours 45 min ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



Comments
RE: "All variables can be used as arrays without explicit..."
"All variables can be used as arrays without explicit definition" is not always true, at least in bash ~3.0. If you define a variable using "local" in a function, this is apparently nearly, if not exactly, the same as using "declare", which as mentioned does define a variable as local when used within a function. If when defining a variable as local you do not also use "-a", then you cannot also use the array initialization notation to treat it as an array; you end up with all initialization values in the first element of the "array" you just created. (Using "declare" unstead of "local" seemed to work just the same in my limited testing.) If you just remove the "local" declaration, your intended array works just fine, but it is now global.
Its nice to know that bash
Its nice to know that bash declare statement can be used to declare variable to accept only numeric values.
a=13 declare -r a echo
a=13
declare -r a
echo $a
a=14
echo
I can not execute this command on my pc, anyone help me?
Are you Using Windows?
It won't work if you are..png)
Perhaps if you leave a few more details...
Mitch Frazier is an Associate Editor for Linux Journal.
is linux so great??
I had the opportunity to use the linux redhat stuff about 5 years ago. It had the same amount of bugs as the windows competitor at the time. I don't understand the big hooplah. Instead of blue-screening, the PC would just shut down.
re: bash
I runned #!/bin/bash
a=13
declare -r a
echo $a
a=14
echo
but it fail , did i miss anything ? i think i did it right with commands..
Nope You Didn't Miss Anything
It's *supposed* to fail, read the paragraph after the script:
Mitch Frazier is an Associate Editor for Linux Journal.
Is there any difference
Is there any difference between using 'declare -r' and 'readonly' to set variables as read only?
No Difference
Although the man page does not explicitly say they are the same, there does not appear to be any difference in the effect that they have or the error message that's produced if you try to change one.
Mitch Frazier is an Associate Editor for Linux Journal.
Exact same
It doesn't explain it anywhere on the page, but yeah they're the same for all practical purposes.
thanks for clarity
I wasn't sure about that either thanks for clearing my confusion.
You can do these with
You can do these with typeset too and it's more portable.
to what?
More portable to what? "help typeset" says "Obsolete. See `declare'." And there's no mention of "typeset" in Posix. I was under the impression that it was a korn-shell-ism, and ksh makes little or no pretense to being a viable substiture for a standard /bin/sh, so I see no reason to worry about compatibility with it. Dash (another widely used bourne/posix shell, based on BSD's ash) has "readonly" but neither declare nor typeset, so for that particular case, I would think that "readonly" (also supported by ksh, fwiw) would be slightly more portable. Aside from that, the only factor I see for choosing between the two is that "typeset" looks like something that may not be supported for much longer.
I didn't say typeset is a
I didn't say typeset is a POSIX standard, but works with more shells, like you said ksh -- and its variants. Well, bash is the default shell on Linux, but ksh is very popular on other Unix-like systems.
The fact that typeset is obsolete in bash is surprised me. I can't see why is it good to removing typeset from bash.
help
Actually, typing "help declare" at the prompt may be quicker/easier than hunting through the very-large man page, at least to get started. (Many people don't realize that bash has built-in help for its built-in commands.)