Chinaunix

标题: while read语句中exit为什么是退出循环,而不退出脚本 [打印本页]

作者: tangrgw    时间: 2015-08-21 15:24
标题: while read语句中exit为什么是退出循环,而不退出脚本
本帖最后由 tangrgw 于 2015-08-21 16:15 编辑
  1. #/bin/bash
  2. cat all.txt|while read line
  3. do
  4.     echo $line
  5.     exit 0
  6. done
  7. echo aaaaaaaaaaaaaaaa
复制代码
执行脚本之后,输出结果:
test
aaaaaaaaaaaaaaaa

这里执行完read第一行之后,使用exit 0,退出的是循环,而不是脚本。如果我要退出脚本怎么处理?
作者: seesea2517    时间: 2015-08-21 15:31
试试这样:
  1. while read line
  2. do
  3.     echo $line
  4.     exit 0
  5. done < all.txt
复制代码

作者: tangrgw    时间: 2015-08-21 15:42
回复 2# seesea2517
不行
[root@otttest rc]# sh isif2.sh
asdf
aaaaaaaaaaaaaaaa
[root@otttest rc]# cat isif2.sh   
#/bin/bash

cat all.txt|while read line
do
    echo $line
    exit 0
done < all.txt

echo aaaaaaaaaaaaaaaa


   
作者: seesea2517    时间: 2015-08-21 15:58
回复 3# tangrgw


    呃……干嘛不原样复制,要加上 cat all.txt 这个头呢?
作者: tuyajie    时间: 2015-08-21 16:07
|管道起了个子shell
作者: tangrgw    时间: 2015-08-21 17:32
回复 5# tuyajie

有什么办法吗?
   
作者: tuyajie    时间: 2015-08-21 17:36
  1.     #/bin/bash
  2. while read line
  3.     do
  4.         echo $line
  5.         exit 0
  6.     done < all.txt
  7.     echo aaaaaaaaaaaaaaaa
复制代码
回复 6# tangrgw
2楼的意思是让你把管道前面的文件写到while 的重定向位置。。


   
作者: Shell_HAT    时间: 2015-08-21 20:02
回复 6# tangrgw


    办法就是照抄2楼代码,不要画蛇添足。
作者: xiangliangyu    时间: 2016-05-11 12:17
blog.uouo123.com/post/811.html
#!/bin/bash
while read line
do
        if [ "$line" == "do" ];then
                exit 2
        fi
        echo $line
done<<<"$(cat 1)"
echo aaa

<<<是bash的扩展,叫做here-string
加上双引号就能一次读一行结果
作者: lll1985911    时间: 2016-05-11 14:14
本帖最后由 lll1985911 于 2016-05-11 14:17 编辑

5楼说的对,管道启了个子shell。
你的exit 0退出的只是管道后面的子shell。可以给all.txt中多增加几行,然后运行看看。

另外,推荐使用:
while read line
do
      ...
done << all.txt
的方式,不要使用cat 加管道的方式。

如果你非要使用cat的方式也行,那么就不要再done后面写什么echo 'aaaaaaaaa'语句了。因为从逻辑上理解done之后的语句都不应该被执行了才对。那么这样就能达到你要的效果了!(当然只是运行效果而已^_^)
如果你一定要在done之后写上echo 'aaaaaaaaaaa',然后问为什么exit 没有退出整个脚本的话,那么原因就是管道启了个子shell,exit退出的只是这个子shell!




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2