Variables getting reset after the while read loop that reads from a pipeline

前端 未结 3 1446
温柔的废话
温柔的废话 2020-11-27 07:45
initiate () {
read -p \"Location(s) to look for .bsp files in? \" loc
find $loc -name \"*.bsp\" | while read
do
    if [ -f \"$loc.bz2\" ]
    then
        continue
         


        
3条回答
  •  轮回少年
    2020-11-27 08:10

    I ran into this problem yesterday.

    The trouble is that you're doing find $loc -name "*.bsp" | while read. Because this involves a pipe, the while read loop can't actually be running in the same bash process as the rest of your script; bash has to spawn off a subprocess so that it can connect the the stdout of find to the stdin of the while loop.

    This is all very clever, but it means that any variables set in the loop can't be seen after the loop, which totally defeated the whole purpose of the while loop I was writing.

    You can either try to feed input to the loop without using a pipe, or get output from the loop without using variables. I ended up with a horrifying abomination involving both writing to a temporary file AND wrapping the whole loop in $(...), like so:

    var="$(producer | while read line; do
        ...
        echo "${something}"
    done)"
    

    Which got me var set to all the things that had been echoed from the loop. I probably messed up the syntax of that example; I don't have the code I wrote handy at the moment.

提交回复
热议问题