加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Bourne Shell退出将无法正常工作

发布时间:2020-12-16 01:45:10 所属栏目:安全 来源:网络整理
导读:我有以下脚本 cat $1 | while read linedo line=`echo $line | tr "[:lower:]" "[:upper:]"` if [ "`echo $line | cut -f1 -d:`" = "foo" ] [ "`echo $line | cut -f2 -d:`" = "bar" ]; then echo 'exsist' exit 1; fidone 一切都可以回应,然后当脚本命中
我有以下脚本

cat $1 | while read line
do
    line=`echo $line | tr "[:lower:]" "[:upper:]"`

    if [ "`echo $line | cut -f1 -d:`" = "foo" ] && 
       [ "`echo $line | cut -f2 -d:`" = "bar" ]; then
        echo 'exsist'
        exit 1;
    fi
done

一切都可以回应,然后当脚本命中退出时,它不会继续前进.有任何想法吗.

谢谢

解决方法

你不需要反斜杠 – 这不是C shell.

问题是while循环是在子shell中退出,但由于它是作为子shell运行的,因此主脚本继续运行.

在上下文中,最简单的修复可能是:

while read line
do
    line=`echo $line | tr "[:lower:]" "[:upper:]"`
    if [ "`echo $line | cut -f1 -d:`" = "foo" ] &&
       [ "`echo $line | cut -f2 -d:`" = "bar" ]; then
        echo 'exist'
        exit 1
    fi
done < $1

如果你必须处理多个文件(‘cat“$@”’而不是’cat $1’),那么你必须更加努力地工作:

cat "$@" |
while read line
do
    line=`echo $line | tr "[:lower:]" "[:upper:]"`
    if [ "`echo $line | cut -f1 -d:`" = "foo" ] &&
       [ "`echo $line | cut -f2 -d:`" = "bar" ]; then
        echo 'exist'
        exit 1
    fi
done
[ $? != 0 ] && exit 1

这将检查由’cat’和’while’组成的管道的退出状态,这是’while’循环的退出状态,如果在’a’开头找到’foo:bar’,则在示例中为1.线.

当然,还有其他方法可以检测到这种情况,例如:

grep -s -q "^foo:bar:" "$@" && exit 1

这比循环版本执行的命令要少得多. (如果你需要允许’^ foo:bar $’,请使用egrep而不是plain grep.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读