views:

42

answers:

2

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.

A: 

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

Marc van Kempen
I done 'export TEST_STRING=0' before the loop but $TEST_STRING still returns 0 after the loop.
Mint
No need to export, just don't use a construct that creates a sub-shell, AKA a pipe.
SiegeX
That's not the way export works or what it's used for. It's used to get a variable *into* a child process, not *out* of it.
Dennis Williamson
+1  A: 

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
SiegeX
Ah thats it, a sub-shell. I knew there was a word for it I just forgot what it was. So it's 3 redirects, huh. Thanks!
Mint
Do you have any links where I can read up further on the 3 redirects '<<<'?
Mint
@Mint: It's not "3 redirects", `<<<` is called a "here string" (`<<` is called a "here doc"). [Here's a doc on here strings and here docs](http://mywiki.wooledge.org/BashGuide/InputAndOutput?highlight=%28here%29%7C%28string%29#Heredocs_And_Herestrings). And from the [manual](http://tiswww.case.edu/php/chet/bash/bashref.html#SEC45).
Dennis Williamson