[Comprehensive explanation of Linux commands] 195. Bash command analysis: detailed explanation of the usage and functions of declare

declare

Declare variables and set or display their values ​​and properties.

grammar

declare [-aAfFgilnrtux] [-p] [name[=value] ...]

The main purpose

  • Displays all variables and values ​​containing the specified attribute
  • Display one or more variables and values ​​containing the specified attribute
  • Display the properties and values ​​of one or more variables
  • Displays the properties and values ​​of all variables and displays the definition of functions
  • Show properties and values ​​of all variables
  • Display properties and values ​​of all global variables
  • Show all function names and function definitions
  • Show only all function names
  • Display one or more function names and function definitions
  • Only display one or more function names
  • Declare global variables (optional: assignment)
  • Declare variables (optional: assignment, attributes)
  • Add and delete attributes of variables (optional: assignment)

Options

  • -fLimit operations or display to function names and function definitions.
  • -FShow only the function name (with line number and source file appended when debugging).
  • -gCreates a global variable when used within a shell function; otherwise ignored.
  • -pDisplays the properties and values ​​of each name.

*Options to set properties:

  • -aCreate an array (if supported).
  • -ACreate an associative array (if supported).
  • -iAdd integer attributes.
  • +iRemove integer attributes.
  • -lAdd the lowercase attribute and the value of the variable will be converted to lowercase.
  • +lRemove lowercase attributes.
  • -nAdd the reference attribute if this option exists.
  • +nRemoves the reference attribute if this option exists.
  • -rAdd read-only attribute.
  • -tAdd tracking properties.
  • +tRemove tracking attributes.
  • -uAdd the uppercase attribute and the value of the variable will be converted to uppercase.
  • +uRemove uppercase attributes.
  • -xAdd export properties.
  • +xRemove export properties.

parameter

  • name(optional): variable name or function name.
  • value(optional): The value of the variable.

return value

declareReturned trueunless you provide an illegal option or an assignment error. For specific conditions that cause exceptions, please see the discussion chapter about exceptions.

example

# 声明变量,当然也欢迎您在这个网站(感谢本项目发起人 @jaywcjlove)查询linux命令。
declare reference_website='https://wangchujiang.com/linux-command/'

# 显示所有包含整型属性的变量和值。
declare -i
# 定义变量b并赋值为3,具有整型属性。
declare -i b=5
# 显示属性,返回 declare -i b="5"。
declare -p b
# 删除整型属性。
declare +i b
# 显示属性,返回 declare -- b="5"。
declare -p b
# 根据变量属性强制转换值的英文大小写。
declare -u uc_var='abc'
declare -l lc_var='ABC'
# 显示'ABC abc';
echo "${uc_var} ${lc_var}"
# 定义函数内的全局变量
function test(){
    
    
  declare -g a=3
  # 或者
  local -g b=3
  # 或者
  c=3
  # 让我们查看它们的属性。
  declare -p a b c
}
# 执行函数。
test
# 返回结果。
# declare -- a="3"
# declare -- b="3"
# declare -- c="3"

# 定义函数外的全局变量
declare a=3
b=3
declare –p a b
# 返回结果如下。
# declare -- a="3"
# declare -- b="3"

# 定义局部变量
function test2(){
    
    
  local -i a=3
  declare -i b=3
}
test2
# 没有该变量(已经被销毁了)
echo "${a} ${b}"
# 因此,我们日常脚本中最常见的类似于'a=3'实际上是声明并赋值了一个全局变量。
# 在接下来的 **讨论** 环节会延伸讨论全局和局部变量问题。
# 注意,不能使用 `+a` 或 `+A` 取消数组,也不能使用 `+r` 取消只读属性。

# 定义只读数组,设置属性的同时定义赋值。
declare -ar season=('Spring' 'Summer' 'Autumn' 'Winter')
# 或者这样。
season=('Spring' 'Summer' 'Autumn' 'Winter')
declare -ar season
# 显示所有数组。
declare -a
# 定义关联数组。

declare -A fruits=(['apple']='red' ['banana']='yellow')
# 显示所有关联数组。
declare -A
# 显示所有变量的属性和值并显示函数的定义,输出很长。
declare
# 显示所有变量的属性和值。
declare -p
# 显示所有全局变量的属性和值。
declare -g
# 显示全部函数名和函数定义。
declare -f
# 只显示全部函数名。
declare -F

# 定义两个函数。
function func_a(){
    
     echo $(date +"%F %T"); }
function func_b(){
    
     cd /; ls -lh --sort=time; }
# 显示一到多个函数名和函数定义。
declare -f func_a func_b
# 只显示一到多个函数名,验证某个名称是否已经定义为函数时有用。
declare -F func_a func_b
# 最好不要让函数名和变量名相同。

discuss

Global and local variables

As the above example points out, we need to understand these concepts when writing programs every day. Here is a brief introduction. Of course, you can also easily search for relevant content.

  • Global variables: They exist throughout the execution of the script as long as they are not deleted.
  • Local variables: defined within a function and deleted after the function is executed.

It is recommended to use commands within functions localand declarecommands outside functions.

Do not define too many global variables in the script, as this may cause unexpected consequences when called by other functions, and it is inconvenient to check out.

Not to mention the lack of necessary comments - ZhuangZhu-74

Relevant information:

  • Coding specifications provided by google
  • Discussion of global variables
  • About declare, typeset, export, local, readonlycommands

Why do declarewe need to define these other commands when we can do it?

Because the meaning of the statement will be clearer, for example:

  • When setting variables for exported properties, export varand declare -x var.
  • Use when declaring variables within a function local.
  • To declare read-only variables, use readonly.
  • typesetSame as declarecommand.

About exceptions

There are many reasons for declarethe failure. For these situations, you can refer to the bash online documentation declaresection (the latest version), or execute the last series of sentences info bashin the view section.declarean attempt is

Notice

This command is a built-in bash command. For related help information, please see helpthe command.
For information on exporting properties, please see the 'export' command.
For an introduction to read-only properties, please see the 'readonly' command.
See the examples section of the 'unset' command for an introduction to reference attributes.

Learn from scratchpython

[Learn python from scratch] 92. Use Python’s requests library to send HTTP requests and process responses
[Learn python from scratch] 91. Use decorators and dictionaries to manage request paths in a simple web application
[Learn python from scratch] 93. Use dictionary management Request path
[Learn python from scratch] 89. Use WSGI to build a simple and efficient Web server
[Learn python from scratch] 88. Detailed explanation of WSGI interface: realize simple and efficient web development
[Learn python from scratch] 87. Manually build an HTTP server in Python Implementation and multi-threaded concurrent processing
[Learn python from scratch] 86. In-depth understanding of the HTTP protocol and its role in browser and server communication
[Learn python from scratch] 85. Application of parallel computing technology in Python process pool
[Learn python from scratch] ] 84. In-depth understanding of threads and processes
[Learn python from scratch] 83. Python multi-process programming and the use of process pools
[Learn python from scratch] 82. Chat program implementation based on multi-threading
[Learn python from scratch] 81. Python more Application of thread communication and queue
[Learn python from scratch] 80. Thread access to global variables and thread safety issues
[Learn python from scratch] 79. Thread access to global variables and thread safety issues
[Learn python from scratch] 78. File download case
[ Learn python from scratch] 77. TCP server programming and precautions
[learn python from scratch] 76. Server and client: key components of network communication
[learn python from scratch] 75. TCP protocol: reliable connection-oriented transmission layer communication protocol
[Learn python from scratch] 74. UDP network program: Detailed explanation of port issues and binding information
[Learn python from scratch] 73. UDP network program - sending data
[Learn python from scratch] 72. In-depth understanding of Socket communication and creation of sockets Method
[Learn python from scratch] 71. Network ports and their functions
[Learn python from scratch] 70. Network communication methods and their applications: from direct communication to routers to connect multiple networks
[Learn python from scratch] 69. Network communication and IP address classification analysis
[Learn python from scratch] 68. Greedy and non-greedy modes in Python regular expressions
[Learn python from scratch] 67. The re module in Python: regular replacement and advanced matching technology
[Learn python from scratch] 66 .In-depth understanding of regular expressions: a powerful tool for pattern matching and text processing
[Learn python from scratch] 65. Detailed explanation of Python regular expression modifiers and their applications
[Learn python from scratch] 64. The re.compile method in Python regular expressions Detailed explanation of usage
[Learn python from scratch] 63. Introduction to the re.Match class and its attributes and methods in regular expressions
[Learn python from scratch] 62. Python regular expressions: a powerful string matching tool
[Learn python from scratch] 61. Detailed explanation and application examples of property attributes in Python
[Learn python from scratch] 60. Exploration generator: a flexible tool for iteration
[Learn python from scratch] 59. Iterator: An efficient tool for optimizing data traversal
[Learn python from scratch] 58. Custom exceptions in Python and methods of raising exceptions
[Learn python from scratch] 57. Use the with keyword in Python to correctly close resources
[Learn python from scratch] 56. The importance and application of exception handling in programming
[Learn python from scratch] 55. Serialization and sum in Python Deserialization, application of JSON and pickle modules
[Learn python from scratch] 54. Writing data in memory
[Learn python from scratch] 53. CSV files and Python’s CSV module
[Learn python from scratch] 52. Reading and writing files - Python file operation guide
[Learn python from scratch] 51. Opening and closing files and their applications in Python
[Learn python from scratch] 49. Object-related built-in functions in Python and their usage
[Learn python from scratch] 48 .Detailed explanation of inheritance and multiple inheritance in Python
[Learn python from scratch] 47. The concept and basic use of inheritance in object-oriented programming
[Learn python from scratch] 46. Analysis of __new__ and __init__ methods and singletons in Python Design Patterns
[Learn python from scratch] 45. Class methods and static methods in Python
[Learn python from scratch] 44. Private properties and methods in object-oriented programming
[Learn python from scratch] 43. Examples in Python object-oriented programming Properties and class attributes
[Learn python from scratch] 42. Built-in properties and methods in Python
[Learn python from scratch] 41. python magic method (2)
[Learn python from scratch] 40. python magic method (1)
[Learn python from scratch] 39. Basic object-oriented syntax and application examples
[Learn python from scratch] 38. How to use and import Python packages
[Learn python from scratch] 37. The use and precautions of Python custom modules
[Learn python from scratch] Learn python] 36. Methods and techniques of using pip for third-party package management in Python
[Learn python from scratch] 35. Python common system modules and their usage
[Learn python from scratch] 34. Detailed explanation of the import and use of Python modules
[ Learn python from scratch] 33. The role of decorators (2)
[Learn python from scratch] 32. The role of decorators (1)
[Learn python from scratch] 31. In-depth understanding of higher-order functions and closures in Python
[From Learn python from scratch】30. In-depth understanding of recursive functions and anonymous functions
【learn python from scratch】29. "Detailed explanation of function parameters" - understand the different uses of Python function parameters
【learn python from scratch】28. Local variables and global variables in Python Variables
[Learn python from scratch] 27. The use of Python functions and nested calls
[Learn python from scratch] 25. Functions: a tool to improve the efficiency of code writing
[Learn python from scratch] 24. String operations and traversal methods in Python
[Learn python from scratch] 23. How to use sets (set) and common operations in Python
[Learn python from scratch] 22. Add, delete, modify, and query dictionary variables in Python
[Learn python from scratch] 21. Python tuples and dictionaries
[Learn python from scratch] 20. Python list operation skills and examples
[Learn python from scratch] 19. Applications of looping through lists and list nesting
[Learn python from scratch] 18. Detailed explanation of the basic operations of Python lists (1)
[From Learning python from scratch】 17. The format method of Python strings (2)
【Learning python from scratch】 16. The format method of Python strings (1)
【Learning python from scratch】 15. In-depth understanding of strings and character set encoding
【From Learning python from scratch】14. Common operations on Python strings (2)
【Learning python from scratch】13. Common operations on Python strings (1)
【Learning python from scratch】12. Python string operations and applications
【Learning python from scratch】 11. Python loop statements and control flow
[Learn python from scratch] 10. Detailed explanation of Python conditional statements and if nesting
[Learn python from scratch] 09. Conditional judgment statements in Python
[Learn python from scratch] 08. Python understands bit operations operator, operator priority
[Learn python from scratch] 07. Detailed explanation of Python operators: assignment, comparison and logical operators
[Learn python from scratch] 06. Use arithmetic operators in Python for calculations and string concatenation
[Learn from scratch] python ] 05. Output and input in Python
[Learn python from scratch] 04. Basics of Python programming: variables, data types and identifiers
[Learn python from scratch] 03. Python interactive programming and detailed explanation of comments
[Learn python from scratch] 02. Introduction to development tools
[Learn python from scratch] 01. Install and configure python

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/133266189