【问题标题】:How to give an empty array to function in bash? [duplicate]如何给一个空数组在 bash 中起作用? [复制]
【发布时间】:2016-11-14 09:35:32
【问题描述】:

我正在学习 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

我不知道传递空数组有什么问题。 知道机制或解决方案的人。请让我知道。 非常感谢。

【问题讨论】:

标签: bash


【解决方案1】:

enter image description here如果位置参数为空,shell 脚本和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

【讨论】:

  • 感谢您的回答。我复制了您的样本并对其进行了测试,但它并没有改变结果。你是如何运行你的代码的?非常感谢。
  • 它按我解释的那样工作。对于您的参考 PFA 屏幕截图。
  • 感谢您再次回答。它在我的环境中仍然不起作用; GNU bash,版本 4.3.42。但是请不要再介意这个问题了。我提到了 Sundeep 上面推荐的其他网站。
猜你喜欢
  • 1970-01-01
  • 2013-10-25
  • 2020-12-31
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2016-08-16
  • 2018-12-04
相关资源
最近更新 更多