码迷,mamicode.com
首页 > 系统相关 > 详细

Shell之declare定义变量

时间:2018-01-09 16:54:27      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:脚本   oat   exp   lis   参数   定义函数   core   let   cut   

实验环境
 ~]# 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定义变量

标签:脚本   oat   exp   lis   参数   定义函数   core   let   cut   

原文地址:http://blog.51cto.com/firelong/2059087

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!