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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)