Shell之declare定义变量
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Shell之declare定义变量相关的知识,希望对你有一定的参考价值。
实验环境
~]# cat /etc/redhat-release
CentOS Linux release 7.3.1611 (Core)
命令说明
declare 与 typeset 命令都是bash的内建命令(builtin commands),两者所实现的功能完全一样,用来设置变量值和属性。
typeset现已弃用,由declare进行替代,可查看帮助手册:
~]# help typeset
typeset: typeset [-aAfFgilrtux] [-p] name[=value] ...
Set variable values and attributes.
Obsolete. See `help declare‘.
~]# help declare
declare: declare [-aAfFgilrtux] [-p] [name[=value] ...]
Set variable values and attributes.
命令选项
typeset 和 declare的选项参数是通用的,下面以declare进行说明:
Declare variables and give them attributes. If no NAMEs are given, display the attributes and values of all variables.
declare [-aAfFgilrtux] [-p] [name[=value] ...]
选项:
-f [name]:列出之前由用户在脚本中定义的函数名称和函数体;
-F [name]:仅列出自定义函数名称;
-g name:在shell函数中可创建全局变量;
-p [name]:显示指定变量的属性和值;
-a name:声明变量为普通数组;
-A name:声明变量为关联数组(支持索引下标为字符串);
-i name :将变量定义为整数型(求值结果仅为整数,否则显示为0);
-r [name[=value]] 或 readonly name:将变量定义为只读(不可修改和删除);
-x name[=value] 或 export name[=value]:将变量设置为环境变量;
PS:使用 + 可取消定义的变量类型,如取消整数变量定义declare +i name。
unset name:取消变量的属性和值,只读变量除外。
Unset values and attributes of shell variables and functions.
使用示例
#!/bin/bash
echo "Set a custom function - func1"
echo
func1 ()
{
echo This is a function.
}
echo "Lists the function body."
echo "============================="
declare -f
echo
echo "Lists the function name."
echo "============================="
declare -F
echo
declare -i var1 # var1 is an integer.
var1=2367
echo "var1 declared as $var1"
var1=var1+1 # Integer declaration eliminates the need for ‘let‘.
echo "var1 incremented by 1 is $var1."
# Attempt to change variable declared as integer.
echo "Attempting to change var1 to floating point value, 2367.1."
var1=2367.1 # Results in error message, with no change to variable.
echo "var1 is still $var1"
echo
declare -r var2=13.36 # ‘declare‘ permits setting a variable property
#+ and simultaneously assigning it a value.
echo "var2 declared as $var2" # Attempt to change readonly variable.
echo
echo "Change the var2‘s values to 13.37"
var2=13.37 # Generates error message, and exit from script.
echo "var2 is still $var2" # This line will not execute.
exit 0 # Script will not exit here.
参考链接
declare Advanced Bash-Scripting Guide
以上是关于Shell之declare定义变量的主要内容,如果未能解决你的问题,请参考以下文章