declare

shell builtinlinux
The declare command is one of the most frequently used commands in Linux/Unix-like operating systems. declare The declare command is a built-in shell command in Bash that declares variables and sets their attributes. It allows for specifying variable types and properties, providing more control over how variables behave in shell scripts.

Quick Reference

Command Name:

declare

Category:

shell builtin

Platform:

linux

Basic Usage:

declare -i number=10

Common Use Cases

  • 1

    Variable typing

    Declare variables with specific attributes and constraints in Bash

  • 2

    Array creation

    Define and manage indexed and associative arrays in shell scripts

  • 3

    Function parameter handling

    Create variables with specific behaviors for function inputs

  • 4

    Script debugging

    Enable variable tracing and error detection in complex scripts

Syntax

declare [options] [name[=value]]...

Options

Option Description
-a Declare array variable
-A Declare associative array (requires Bash 4+)
-f Restrict to function names and definitions
-F Display function names only (without definitions)
-g Create global variables when used in a shell function
-i Declare integer variable
-l Convert variable value to lowercase
-n Declare name reference to another variable
-p Display attributes and values of each name
-r Make variables read-only (cannot be unset or changed)
-t Give each variable the trace attribute
-u Convert variable value to uppercase
-x Export variables to environment for child processes

Examples

How to Use These Examples

The examples below show common ways to use the declare command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.

#

Basic Examples:

# Declare a simple variable
declare var1="Hello World"
echo $var1
# Declare an integer variable declare -i num=42 echo $num
# Declare a read-only variable declare -r readonly_var="Cannot change this" echo $readonly_var
# Declare an array declare -a my_array=("apple" "banana" "cherry") echo ${my_array[1]}
# Declare an associative array (requires Bash 4+) declare -A user_info user_info=([name]="John" [age]=30 [city]="New York") echo ${user_info[name]}

Advanced Examples:

# Declare and export a variable in one step
declare -x exported_var="This is exported to child processes"
bash -c 'echo $exported_var'
# Declare a case-insensitive variable (will convert to lowercase) declare -l lowercase_var="CONVERT THIS TO LOWERCASE" echo $lowercase_var # Declare a case-insensitive variable (will convert to uppercase) declare -u uppercase_var="convert this to uppercase" echo $uppercase_var # Declare a variable with capitalized value declare -c capitalize_var="first letter capitalized" echo $capitalize_var # Automatically treat variable as a reference to another variable declare -n ref=original original="Reference example" echo $ref # Show all declared functions declare -f # Show a specific function definition declare -f function_name # List all variable names and values in the current scope declare -p # Show only arrays declare -a

Try It Yourself

Practice makes perfect! The best way to learn is by trying these examples on your own system with real files.

Understanding Syntax

Pay attention to the syntax coloring: commands, options, and file paths are highlighted differently.

Notes

Key Features of declare:

  • Type declaration: Allows explicit declaration of variable types like integers, arrays, etc.
  • Attribute control: Set attributes that affect variable behavior (read-only, export, etc.)
  • Debugging: Used to display variables and functions for debugging purposes
  • Variable scope control: Helps manage variable scopes with the -g option

Working with Arrays:

Bash supports both indexed and associative arrays:

  • Indexed arrays (-a): Standard arrays with numeric indices starting at 0
  • Associative arrays (-A): Key-value pairs where keys can be strings (Bash 4.0+)
  • Access elements with ${array[index]} or ${array[key]}
  • Access all elements with ${array[@]} or ${array[*]}
  • Get array length with ${#array[@]}

Integer Variables:

When a variable is declared as an integer with -i:

  • Arithmetic operations can be performed without using expr or $(())
  • Non-integer values assigned to the variable are evaluated as arithmetic expressions
  • Invalid expressions result in setting the variable to 0

Read-only Variables:

Variables declared with -r cannot be changed or unset:

  • Attempting to modify them results in an error
  • Read-only attribute cannot be removed once set
  • Similar to constants in other programming languages

Name References:

Using -n creates a reference or pointer to another variable:

  • Useful for creating functions that modify variables passed as parameters
  • Avoids the need for eval or complex indirection syntax
  • Available in Bash 4.3 and later

Case Modification:

Options for automatic case conversion:

  • -l: Converts value to lowercase when assigned
  • -u: Converts value to uppercase when assigned
  • -c: Capitalizes the first character of the value when assigned

Comparing with typeset:

The typeset command is mostly identical to declare:

  • typeset is primarily for ksh compatibility
  • declare is the preferred command in Bash scripts
  • Both commands accept the same options

Best Practices:

  • Always declare array variables before using them
  • Use -r for constants that should never change
  • Use -i for variables used in arithmetic
  • Use declare -p varname for debugging
  • Be cautious with -g as it affects variable scope

Tips & Tricks

1

Use the -a option to declare an array variable

2

Use the -A option to declare an associative array variable

3

Use the -i option to declare an integer variable

4

Use the -r option to declare a readonly variable

5

Use the -x option to declare an exported variable

Common Use Cases

Variable typing

Declare variables with specific attributes and constraints in Bash

Array creation

Define and manage indexed and associative arrays in shell scripts

Function parameter handling

Create variables with specific behaviors for function inputs

Script debugging

Enable variable tracing and error detection in complex scripts

Variable scope control

Control variable visibility and exportability to child processes

Related Commands

These commands are frequently used alongside declare or serve similar purposes:

Use Cases

1

Variable typing

Declare variables with specific attributes and constraints in Bash

2

Array creation

Define and manage indexed and associative arrays in shell scripts

3

Function parameter handling

Create variables with specific behaviors for function inputs

4

Script debugging

Enable variable tracing and error detection in complex scripts

5

Variable scope control

Control variable visibility and exportability to child processes

Learn By Doing

The best way to learn Linux commands is by practicing. Try out these examples in your terminal to build muscle memory and understand how the declare command works in different scenarios.

$ declare
View All Commands