Latest web development tutorials

Linux declare command

Linux command Daquan Linux command Daquan

Linux declare shell command is used to declare variables.

declare a shell command in the first syntax used to declare variables and set the properties of the variable ([rix] is the attribute variables), in the second syntax can be used to display the shell functions. Without adding any parameters, it will all shell variables and function display (with the effect of the implementation of the same set of instructions).

grammar

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

Parameter Description:

  • + "-" To specify variable properties are available, "+" is canceled variables set attributes.
  • -f Display only function.
  • r the variable is set to read-only.
  • x specified variable will be the environment variables for use outside the shell program.
  • i [Settings] can be numeric, string, or expression.

Examples

Declare integer variables

# declare -i ab //声明整数型变量
# ab=56 //改变变量内容
# echo $ab //显示变量内容
56

Change variable properties

# declare -i ef //声明整数型变量
# ef=1  //变量赋值(整数值)
# echo $ef //显示变量内容
1
# ef="wer" //变量赋值(文本值)
# echo $ef 
0
# declare +i ef //取消变量属性
# ef="wer"
# echo $ef
wer

Set the variable read-only

# declare -r ab //设置变量为只读
# ab=88 //改变变量内容
-bash: ab: 只读变量
# echo $ab //显示变量内容
56

Declare an array variable

# declare -a cd='([0]="a" [1]="b" [2]="c")' //声明数组变量
# echo ${cd[1]}
b //显示变量内容

# echo ${cd[@]} //显示整个数组变量内容
a b c

Display Function

# 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 command Daquan Linux command Daquan