zoukankan      html  css  js  c++  java
  • shell中使用管道符需要注意的点

    写个监控采集脚本有一处使用了管道符,运行结果出乎意料,特来mark下

    结论:管道符和括号会fork出一个子进程,如果在子进程的工作区间内调用exit则退出的只是当前的子进程,不会退出主进程

    测试管道符

    cat test.sh
    #!/bin/bash function work_pipeline(){ seq 3 |while read line; do echo $line if (($line >2));then echo "I'm going to exit" exit fi done } function work_quote(){ for line in $(seq 3) ; do echo $line if (($line >2));then echo "I'm going to exit" exit fi done } function main(){ for i in $(seq 2);do work_pipeline done } main

    运行结果

    工作函数work_pipeline 在mian函数中被调用了两次,每次工作函数在遇到2后都会执行exit,但是exit退出的是子进程

     sh test.sh
    1
    2
    3
    I'm going to exit
    1
    2
    3
    I'm going to exit

    如果想达到退出主进程的功能需要使用work_quote函数

    # 将main函数改写成
    function main(){
    for i in $(seq 2);do
      work_quote
    done
    } 
    # 运行结果
    1
    2
    3
    I'm going to exit

    测试括号

    和管道符一样会创建子进程,exit退出的只是子进程

    # 将main函数改写成
    function main(){
    for i in $(seq 2);do
      (work_quote)
    done
    } 
    # 运行结果
    1
    2
    3
    I'm going to exit
    1
    2
    3
    I'm going to exit

    补充一个错误使用重定向的案例

    ll >t.txt &>/dev/null
    # t.txt会为空
  • 相关阅读:
    css样式的六种选择器
    css 颜色表示法
    css 文本设置
    “http”和“https”的区别是什么?优缺点是什么?
    Httpclient
    接口认证:Bearer Token(Token 令牌)
    哪个参数用来区分请求来自客户(手机)端还是服务器(PC)端?
    常用的HTTP响应头
    Http 请求头包含哪些信息?
    单例集合的体系
  • 原文地址:https://www.cnblogs.com/Bccd/p/12679164.html
Copyright © 2011-2022 走看看