Linux declare Command

Linux 命令大全Linux Command Encyclopedia

The Linux declare command is used to declare shell variables.

declare is a shell command. In the first syntax, it can be used to declare variables and set variable attributes ([rix] refers to the variable attributes). In the second syntax, it can be used to display shell functions. If no parameters are added, all shell variables and functions will be displayed (the same effect as executing the set command).

Syntax

declare [+/-][rxi][变量名称=设置值] 或 declare -f

Parameter Description:

  • +/-  "-" can be used to specify variable attributes, while "+" cancels the attributes set for the variable.
  • -f  Only displays functions.
  • r  Sets the variable to read-only.
  • x  The specified variable becomes an environment variable, available for use by programs outside the shell.
  • i  [Setting value] can be a numeric value, string, or expression.

Examples

Declaring an integer variable

Example

# declare -i ab //Declare an integer variable
# ab=56 //Change the variable content
# echo $ab //Display the variable content
56

Changing variable attributes

Example

# declare -i ef //Declare an integer variable
# ef=1 //Variable assignment (integer value)
# echo $ef //Display the variable content
1
# ef="wer" //Variable assignment (text value)
# echo $ef
0
# declare +i ef //Cancel the variable attribute
# ef="wer"
# echo $ef
wer

Setting a variable to read-only

Example

# declare -r ab //Set the variable to read-only
# ab=88 //Change the variable content
-bash: ab: read-only variable
# echo $ab //Display the variable content
56

Declaring an array variable

Example

# declare -a cd='(
# echo ${cd[1]}
b //Displaying the variable content

# echo ${cd[@]} //Display the entire array variable content
a b c

Displaying functions

Example

# declare -f
command_not_found_handle ()
{
  if [ -x /usr/lib/command-not-found ]; then
    /usr/bin/python /usr/lib/command-not-found -- $1;
    return $?;
  else
    if [ -x /usr/share/command-not-found ]; then
      /usr/bin/python /usr/share/command-not-found -- $1;
      return $?;
    else
      return 127;
    fi;
  fi
}

Linux 命令大全Linux Command Encyclopedia

Other Extensions