Open In App

declare command in Linux with Examples

Last Updated : 25 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
News Follow

The built-in is a powerful built-in feature of the Bash shell. It allows users to declare and set attributes for variables and functions, enabling better control over their behavior. By understanding how to use declare, you can manage variables and functions more effectively in your shell scripts.

This guide provides a detailed explanation of the declare command with examples, usage scenarios, and common options to help you get the most out of it.

Syntax

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

Basic declare Command Example

In this example, we will declare a variable using the declare command.

Bash

The output of the above typed commands is as follow:

Key Options for declare Command

1. -p:

This is used to displays the options and attributes of each variable name if it is used with name arguments.

Example:

2. -f:

Each name is treated as the name of function, not variable. So you can say this option restrict action or display to function names and definitions.

declare -f

3. -F:

When showing information regarding a function, it show only the function’s name and attributes. So the contents of the function will not be displayed.

declare -F

4. -g:

It causes all operations on variables to take effect in global scope.

Example:

function myfunc {
declare -g myglobal="I am global"
}
myfunc
echo $myglobal # Prints "I am global"

Note: For more details, you can use –help option with “declare” command as follows:

Conclusion

The declare command in Bash is an incredibly versatile tool for managing variables and functions. By using its various options, you can control how variables behave within your scripts—whether as integers, arrays, read-only values, or exported to subshell.

Additionally, declare helps you manage function definitions and display variable attributes, making it an essential part of advanced shell scripting.

What does the declare command do in Bash?

The declare command is used to declare variables and functions, set their attributes (such as readonly or integer), and display their values or definitions.

How do I declare an array in Bash?

You can declare an array using the -a option:

declare -a myarray

Can I make a variable read-only with declare?

Yes, the -r option allows you to declare a variable as read-only, preventing its value from being modified.

How do I display all function definitions using declare?

Use the -f option to display all function definitions:

declare -f

Next Article

Similar Reads

three90RightbarBannerImg