如何避免使用while和find的subshel​​l行为? [英] How to avoid subshell behaviour using while and find?

查看:169
本文介绍了如何避免使用while和find的subshel​​l行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我自己陷入了困境,所以我提出了一个问题,并在此给出了答案.如果find遍历命令找到的内容,则在bash执行该命令.因此,您无法在结果中填充数组并在循环后使用它.

Because I trapped into this myself, I asked a question and did give also the answer here. If find iterates over what the command did find, this is executed from bash in a subshell. So you can not fill an array with results and use it after your loop.

推荐答案

您必须将语法从以下位置更改:

You have to change the syntax from:

i=0
find $cont_dirs_abs -type l -exec test -e {} \; -print0 | while IFS= read -r -d '' lxc_storage_abspath; do
    lxcname=${lxc_storage_abspath##*/}
    ...
    lxcnames[$i]="$lxcname"
    let "i+=1"
done

i=0
while IFS= read -r -d '' lxc_storage_abspath; do
    lxcname=${lxc_storage_abspath##*/}
    ...
    lxcnames[$i]="$lxcname"
    let "i+=1"
done < <(find $cont_dirs_abs -type l -exec test -e {} \; -print0)

就我而言,在此循环之后,我可以访问bash数组$lxcnames:

In my case i can after this loop access the bash array $lxcnames:

i=0
for lxcname in ${lxcnames[*]}; do
    ...
done

希望对任何人都有帮助.

Hope that helps anybody.

这篇关于如何避免使用while和find的subshel​​l行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆