加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Bash Shell之declare定义变量

发布时间:2020-12-15 20:07:11 所属栏目:安全 来源:网络整理
导读:实验环境 ~]# cat /etc/redhat-release CentOS Linux release 7.3.1611 (Core) 命令说明 declare 与 typeset 命令都是bash的内建命令(builtin commands),两者所实现的功能完全一样,用来设置变量值和属性。 typeset现已弃用,由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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读