2016-11-14 19 views
1

我在學習bash。 現在我想給一個函數一個空的數組。但是,它不起作用。請參考下面,如何給一個空數組在bash中的功能?

function display_empty_array_func() { 
    local -a aug1=$1 
    local -a aug2=${2:-no input} 
    echo "array aug1 = ${aug1[@]}" 
    echo "array aug2 = ${aug2[@]}" 
} 

declare -a empty_array=() 

display_empty_array_func "${empty_array[@]}" "1" 

的輸出以下,

array aug1 = 1 # I expected it is empty 
array aug2 = no input # I expected it is 1 

在我的理解,引用變量讓我們舉一個空的變量, 像下面,

function display_empty_variable_func() { 
    local aug1=$1 
    local aug2=${2:-no input} 
    echo "variable aug1 = ${aug1}" 
    echo "variable aug2 = ${aug2}" 
} 

display_empty_variable_func "" "1" 

而且其輸出如下

variable aug1 = # it is empty as expected 
variable aug2 = 1 # it is 1 as expected 

我不知道傳遞空數組是什麼問題。 知道機制或解決方案的人。請讓我知道它。 非常感謝。

+2

這可能幫助:https://stackoverflow.com/questions/16461656/bash-how-to-pass-array-as-an-argument-to-a-function – Sundeep

回答

0

enter image description here如果位置參數爲空,shell腳本將不會考慮該值,而是將下一個非空值作爲其值(位置參數值)。 如果我們想取空值,我們必須把這個值放在引號中。

Ex: I'm having small script like 
cat test_1.sh 
#!/bin/bash 

echo "First Parameter is :"$1; 

echo "Second Parameter is :"$2; 

case -1 
If i executed this script as 
sh test_1.sh 

First Parameter is : 

Second Parameter is : 

Above two lines are empty because i have not given positional parameter values to script. 

case-2 
If i executed this script as 
sh test_1.sh 1 2 

First Parameter is :1 

Second Parameter is :2 

case-2 
If i executed this script as 
sh test_1.sh 2 **# here i given two spaces in between .sh and 2 and i thought 1st param is space and second param is 2 but** 

First Parameter is :2 

Second Parameter is : 

The output looks like above. My first statement will apply here. 

case-4 
If i executed this script as 
sh test_1.sh " " 2 

First Parameter is : 

Second Parameter is :2 

Here i kept space in quotes. Now i'm able to access the space value. 

**This will be help full for you. But for your requirement please use below code.** 

In this you have **quote** the space value(""${empty_array[@]}"") which is coming from **an empty array**("${empty_array[@]}"). So you have to use additional quote to an empty array. 

function display_empty_array_func() { 
    local -a aug1=$1 
    local -a aug2=${2:-no input} 
    echo "array aug1 = ${aug1[@]}" 
    echo "array aug2 = ${aug2[@]}" 
} 

declare -a empty_array=() 

display_empty_array_func ""${empty_array[@]}"" "1" 

The output is: 
array aug1 = 
array aug2 = 1 
+0

感謝你回答。我複製了你的樣本並進行了測試,但沒有改變結果。你是如何運行代碼的?非常感謝你。 – mora

+0

正如我所解釋的那樣工作。對於你的參考PFA截圖。 – learner

+0

感謝您再次回答。它在我的環境中仍然不起作用; GNU bash,版本4.3.42。但請不要再在意這個問題了。我提到了Sundeep上面推薦的其他站點。 – mora