How to do a while loop with a string redirected in

2020-06-06 05:54发布

问题:

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.