shell脚本使用 $? 记录返回值

  在shell脚本中,使用 $? 来获取上一次命令执行时的返回状态。实际使用中需要注意 $? 可能会被清零或覆盖,最好先使用

中间变量存起来,以后使用该中间变量;请看如下几种案例的 $? 值的变化:

  1)shell A文件 调用  shell B文件

      shell B文件:①若有 $?=2

            ② exit  【退回到shell A文件】

      shell A文件:此时拿到的 $?=2

 

  2) shell A文件 调用  shell B文件

      shell B文件:① 若有 $?=2

            ② if [ $? -ne 0 ]; then    【条件判断为真】

                                          exit  【退回到shell A文件】

           if

       shell A文件:此时拿到的 $?=0

 

  3) shell A文件 调用  shell B文件

       shell B文件:① 若有 $?=2

             ② if [ $? -eq 0 ]; then    【条件判断为假】

                                          .........

             if

                ③  exit  【退回到shell A文件】

       shell A文件:此时拿到的 $?=0

 

  4) shell A文件 调用  shell B文件

      shell B文件:① 若有 $?=2

                 xxxyyyy...

             ② exit 4  【退回到shell A文件】

       shell A文件:此时拿到的 $?=4

 

posted @   长颈鹿也落枕  阅读(415)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
欢迎这位怪蜀黍来到《shell脚本使用 $? 记录返回值 - 长颈鹿也落枕 - 博客园》
点击右上角即可分享
微信分享提示