如何使用重定向到其中的字符串执行while循环 [英] How to do a while loop with a string redirected into it

查看:13
本文介绍了如何使用重定向到其中的字符串执行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,这正是我想要的.我正在使用 while 循环,以便它循环遍历 $HTTP_LINKS 中的每个换行符,而不仅仅是字符串中的单词.(我不想在 IFS 设置为 的情况下使用 for 循环)

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 )

我想也许我可以做这样的事情

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 的想法是正确的,但您需要通过 <<< 使用Here Strings"句法.您不能在第一个 snipit 之外访问 $TEST_STRING,因为管道创建了一个子外壳;使用 here-string 不会.另外,请确保引用 "$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
http://www.bbb.com")

unset TEST_STRING; 

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

echo $TEST_STRING

输出

2

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

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