天天看點

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.           

指令選項

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]:将變量設定為環境變量;           
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.
           

參考連結

繼續閱讀