我正在学习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
我不知道传递空数组有什么问题。 知道机制或解决方案的人。请让我知道。 非常感谢你。
答案 0 :(得分:0)
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