Bash 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

转载于:https://blog.51cto.com/firelong/2059087

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值