How to avoid subshell behaviour using while and find? [duplicate]

你离开我真会死。 提交于 2019-12-11 16:30:58

问题


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.


回答1:


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

to

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)

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.



来源:https://stackoverflow.com/questions/55239979/how-to-avoid-subshell-behaviour-using-while-and-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!