How to do a while loop with a string redirected into it

有些话、适合烂在心里 提交于 2019-12-04 14:32:23

问题


Im trying to loop though a string with HTTP links inside and newlines, I want to loop over a line at a time.

At the moment I have

echo -e "$HTTP_LINKS" | while read HTTP_S_LINK ; do
    TEST_STRING="test"
done

But this way I don't have access to the TEST_STRING out side the loop, which is what I want. I'm using the while loop so that it will loop though each newline in $HTTP_LINKS and not just the words in the string. (I don't want to use a for loop with IFS set to \n)

I thought maybe I could just do something like this

#!/bin/bash
while read HTTP_S_LINKS
do   
    TEST_STRING="test2"
done < $HTTP_LINKS

But of course this doesn't work as $HTTP_LINKS contains a string and not a link to a file.


回答1:


You had the right idea with your 2nd snipit but you need to use 'Here Strings' via the <<< syntax. You cant access $TEST_STRING outside of your first snipit because the pipe creates a sub-shell; using the here-string does not. Also, make sure you quote "$HTTP_LINKS" otherwise you'll lose the newlines.

#!/bin/bash

HTTP_LINKS=$(echo -e "http://www.aaa.com\nhttp://www.bbb.com")

unset TEST_STRING; 

while read url; 
do 
    ((TEST_STRING++))
done <<<"$HTTP_LINKS"

echo $TEST_STRING

Output

2



回答2:


If you initialize and export the TEST_STRING variable outside the loop you should have access to it after the loop.



来源:https://stackoverflow.com/questions/3177507/how-to-do-a-while-loop-with-a-string-redirected-into-it

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