while read shell 脚本中的行 - 如何停止循环?

while read shell 脚本中的行 - 如何停止循环?

我在这里阅读了一个可以使用的教程

while read line
do 
wget -x "http://someurl.com/${line}.pdf" -o ${line}.pdf
done < inputfile

然而,该脚本继续运行,$line 不包含任何值。如果下一行为空或出现一些“信号”单词,我该如何更改脚本停止的代码。

感谢您的帮助

答案1

以下是让 while 循环停止在 0 长度值上的方法line

#!/usr/bin/bash
while read line
do
    if [[ -z $line ]]
    then
         exit
    fi
    wget -x "http://someurl.com/${line}.pdf" 
done < inputfile

我认为你真正的问题可能在于“http”之前不匹配的双引号字符,或者“inputfile”末尾不匹配的反引号字符。在尝试我的代码示例之前,您应该清理引用。

答案2

 while read line && [ "$line" != "quit" ]; do # ...

或者停在空行处:

 while read line && [ "$line" != "" ]; do # ...

或者

 while read line && [ -n "$line" ]; do # ...

关于不同的主题:

"http://someurl.com/$line.pdf" -o "$line.pdf"

您不需要花括号,但您应该在最后一个变量扩展周围使用双引号。

答案3

        line=\ ; PS4='${#line}: + '
        while   read line <&$((${#line}?0:3))
        do      : "$line"
        done    <<msg 3</dev/null
        one nice thing about allowing shell expansions to self test
        is  that the shell already has mechanisms in place for the
        evaluation. its doing it all the time anyway. theres almost
        nothing for you to do but to let it fall into place.
        For example:
        ${line##*[ :: i doubt very seriously the shell will read any of this :: ]*}
msg

1: + read line
59: + : 'one nice thing about allowing shell expansions to self test'
59: + read line
58: + : 'is  that the shell already has mechanisms in place for the'
58: + read line
59: + : 'evaluation. its doing it all the time anyway. theres almost'
59: + read line
52: + : 'nothing for you to do but to let it fall into place.'
52: + read line
12: + : 'For example:'
12: + read line
0: + : ''
0: + read line

或者,在阅读空行后立即休息......

while   read line && ${line:+":"} break
do    : stuff
done

...会很好地工作。

相关内容