1. 程式人生 > >Shell之declare定義變量

Shell之declare定義變量

cut permits ado shell 函數 變量 follow mit 否則

實驗環境
 ~]# 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定義變量