重置数组并用 bash 脚本中的值填充它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28737493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Resetting an array and filling it with values in a bash script
提问by Alex
I wanted to know the "right" way to do this. Basically, I have a list of files that are in an array called current
. This is declared as a global variable that looks like this: current=()
. I have successfully put all the files in this array. But now, I am going through and parsing arguments to filter out these files and directories.
我想知道这样做的“正确”方法。基本上,我有一个名为current
. 这被声明为一个全局变量,看起来像这样:current=()
。我已成功将所有文件放入此数组中。但是现在,我正在通过解析参数来过滤掉这些文件和目录。
For example, to implement the -name '*.pattern'
command, I pass in the pattern
to process_name()
which does this:
例如,要实现该-name '*.pattern'
命令,我将传入执行此操作的pattern
to process_name()
:
process_name ()
{
local new_cur=()
for i in "${current[@]}"; do
if [[ "$i" == "" ]]; then
new_cur+=("$i")
fi
done
current=( "${new_cur[@]}" )
}
After the loop finishes I want to "clear" my current
array. Then I want to loop over the new_cur
array, and basically make it equal to current
, or if I can, just do something like $current = $new_cur
(although I know this won't work).
循环完成后,我想“清除”我的current
数组。然后我想循环遍历new_cur
数组,并基本上使它等于current
,或者如果可以的话,就做类似的事情$current = $new_cur
(尽管我知道这行不通)。
I've tried doing this after the for loop (in process_name()
), but my array current
doesn't actually change:
我试过在 for 循环(in process_name()
)之后这样做,但我的数组current
实际上并没有改变:
current=( "${new_cur[@]}" )
Is there a good way to do this? Or a right way to do this?
有没有好的方法可以做到这一点?或者正确的方法来做到这一点?
采纳答案by pynexj
You can simply clone an array using array1=( "${array2[@]}" )
. For example:
您可以简单地使用array1=( "${array2[@]}" )
. 例如:
[STEP 100] $ echo $BASH_VERSION
4.3.33(1)-release
[STEP 101] $ cat foo.sh
current=(aa bb cc)
process_name ()
{
local new_cur=()
for i in "${current[@]}"; do
if [[ "$i" == "" ]]; then
new_cur+=("$i")
fi
done
current=( "${new_cur[@]}" )
}
process_name aa
for i in "${current[@]}"; do
printf '%s\n' "$i"
done
[STEP 102] $ bash foo.sh
aa
[STEP 103] $
回答by anubhava
To reset an array just use:
要重置数组,只需使用:
current=()
This will delete old entries and declare a 0 element array.
这将删除旧条目并声明一个 0 元素数组。