2013-11-02 57 views
11

對不起這麼天真的問題 - 我只是嘗試undertand ...爲什麼在bash腳本中需要「declare -f」和「declare -a」?

例如 - 我有:

$ cat test.sh 
#!/bin/bash 
declare -f testfunct 

testfunct() { 
echo "I'm function" 
} 

testfunct 

declare -a testarr 

testarr=([1]=arr1 [2]=arr2 [3]=arr3) 

echo ${testarr[@]} 

當我運行它,我得到:

$ ./test.sh 
I'm function 
arr1 arr2 arr3 

所以在這裏是一個問題 - 我必須(如果必須...)在這裏插入declare? 隨着它 - 或沒有它的作品相同...

我可以理解,例如declare -i vardeclare -r var。但是什麼是-f(聲明函數)和-a(聲明數組)?

感謝您的提示和鏈接。

+1

declare'的'最常見的用途是函數,其中給定的任何標誌時,它的行爲與'local'內部。對於某些數據類型也是必要的,即。 '爲關聯數組聲明-A'。 'declare -g'通常是一個非常有用的特性,當它想要完全明確給讀者時,你有意*指向函數內的全局函數,而不是忘記聲明它並使其全局隱式。 –

回答

12

declare -f functionname用於輸出功能functionname的定義,如果它存在,並且絕對不能聲明functionname是/將是一個函數。看:

$ unset -f a # unsetting the function a, if it existed 
$ declare -f a 
$ # nothing output and look at the exit code: 
$ echo $? 
1 
$ # that was an "error" because the function didn't exist 
$ a() { echo 'Hello, world!'; } 
$ declare -f a 
a() 
{ 
    echo 'Hello, world!' 
} 
$ # ok? and look at the exit code: 
$ echo $? 
0 
$ # cool :) 

所以你的情況,declare -f testfunct不會做任何事情,除了可能如果testfunct存在,它將輸出在stdout它的定義。

5

declare -f允許您列出所有已定義的功能(或來源)及其內容。使用的

實施例:

[ ~]$ cat test.sh 
#!/bin/bash 

f(){ 
    echo "Hello world" 
} 

# print 0 if is defined (success) 
# print 1 if isn't defined (failure) 
isDefined(){ 
    declare -f "$1" >/dev/null && echo 0 || echo 1 
} 

isDefined f 
isDefined g 
[ ~]$ ./test.sh 
0 
1 
[ ~]$ declare -f 
existFunction() 
{ 
    declare -f "$1" > /dev/null && echo 0 || echo 1 
} 
f() 
{ 
    echo "Hello world" 
} 

然而,由於巧妙地說下面gniourf_gniourf:它最好使用declare -F來測試功能的存在。

+1

要檢查函數是否存在,最好使用'declare -F'。 –

+0

是的,我同意。我將編輯我的帖子:) –

4

據我所知,-a選項本身沒有任何實際意義,但是我認爲在聲明數組時可讀性更好。當它與其他選項組合以生成特殊類型的數組時,它會變得更有趣。

例如:

# Declare an array of integers 
declare -ai int_array 

int_array=(1 2 3) 

# Setting a string as array value fails 
int_array[0]="I am a string" 

# Convert array values to lower case (or upper case with -u) 
declare -al lowercase_array 

lowercase_array[0]="I AM A STRING" 
lowercase_array[1]="ANOTHER STRING" 

echo "${lowercase_array[0]}" 
echo "${lowercase_array[1]}" 

# Make a read only array 
declare -ar readonly_array=(42 "A String") 

# Setting a new value fails 
readonly_array[0]=23 
+0

顯然'-l'和'-u'只是bash 4+。 – Kevin