如何做一个while循环使用重定向到它串 [英] How to do a while loop with a string redirected into it

查看:221
本文介绍了如何做一个while循环使用重定向到它串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着去环,虽然里面HTTP链接和换行符的字符串,我要循环线路在同一时间。

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

目前,我有

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

不过这样一来,我没有访问TEST_STRING出的圈,这就是我想要的。
我使用whil​​e循环,使其循环尽管在$ HTTP_LINKS而不仅仅是字符串中的字,每个换行。 (我不想用一个for循环与IFS设置为\\ n)

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

不过,当然这不工作为$ HTTP_LINKS包含一个字符串,而不是一个链接到一个文件中。

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

推荐答案

您曾与你的第二snipit正确的想法,但需要通过使用'这里字符串'的&LT;&LT;&LT; 语法。你不能访问 $ TEST_STRING 你的第一个snipit之外,因为管道创建一个子shell;使用下面的字符串没有。此外,请确保你引用$ HTTP_LINKS,否则你将失去换行。

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

输出

2

这篇关于如何做一个while循环使用重定向到它串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆