[英]Bash array fails to populate if function is executed as if condition
我有一个 function 填充全局 bash 数组
#!/bin/bash
# Array to store debugger IDs
ID=()
fill_id()
{
for i in 1 2 3 4 5
do
ID+=( $i )
done
echo "fill_ids - entries in ID: ${#ID[*]}"
}
如果直接调用 function,则填充数组并将条目计数打印为 5
fill_id
echo "main - entries in ID: ${#ID[*]}"
Output
fill_ids - entries in ID: 5
main - entries in ID: 5
但是if
在条件中调用 function 则条目计数打印为 0
if (fill_id)
then
echo "main - entries in ID: ${#ID[*]}"
fi
Output
fill_ids - entries in ID: 5
main - entries in ID: 0
fill_fd
的返回值也不影响任何东西。
you are executing function in a subshell so it changes variable of child shell which is not visible in parent shell culprit is "()" you can debug it with printing shell id - see bellow:
#!/bin/bash
# Array to store debugger IDs
ID=()
echo $BASHPID
fill_id()
{
for i in 1 2 3 4 5
do
ID+=( $i )
done
echo $BASHPID
echo "fill_ids - entries in ID: ${#ID[*]}"
}
if (fill_id)
then
echo "main - entries in ID: ${#ID[*]}"
fi
当您直接调用 function (不带子外壳)时,它会正确更改您的变量。
像这样:
if fill_id
then
echo "main - entries in ID: ${#ID[*]}"
fi
只是不要在子shell中执行 function 。
if fill_id
then
echo "main - entries in ID: ${#ID[*]}"
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.