美文网首页
Shell 脚本中的exit状态解释

Shell 脚本中的exit状态解释

作者: 老率的IT私房菜 | 来源:发表于2021-10-26 01:38 被阅读0次

命令的返回值是其退出状态,退出状态用于检查命令执行的结果(成功/失败)。如果退出状态为0,则命令执行成功。如果命令失败,则退出状态为非零。

下面表格中是返回值对应着退出状态的解释:

返回值退出状态

0成功

非0状态失败

2用法不正确

126不是可执行文件

127没有找到指令

$?特殊变量

shell中的变量名$?是一个特殊的内置变量,可以获取最后一次执行命令的退出状态。

在执行shell函数后,$?返回函数中最后一次执行命令的退出状态。

在执行shell脚本后,$?返回脚本中最后一次执行命令的退出状态。

包含退出状态的脚本实例

以下exit_status.sh脚本显示了几种退出状态:

[root@localhost scripts]# vim exit_status.sh

#! /bin/bash

echo -e "Successful execution"

echo -e "====================="

echo "hello world"

# 退出状态为0,因为命令执行是成功的。

echo "Exit status" $?

echo .

echo -e "Incorrect usage"

echo -e "====================="

ls --option

# 使用了错误的用法,所以退出状态为2。

echo "Exit status" $?

echo .

echo -e "Command Not found"

echo -e "====================="

bashscript

# 退出状态为127,因为该脚本或者命令不存在。

echo "Exit status" $?

echo .

echo -e "Command is not an executable"

echo -e "============================="

touch execution.sh

ls -l execution.sh

./execution.sh

# 退出状态为126,因为该文件没有执行权限。

echo "Exit status" $?

echo .

echo -e "Custom status"

echo -e "====================="

function test1(){

  if [ ! -x "./execution.sh" ]; then

    echo "\"./execution.sh\" no execute permission!!"

    return 66

  fi

}

test1

# 退出状态为66,函数test1中判断文件是否不存在,不存在就返回echo语句,并定义了返回值。

echo "Exit status" $?

下面是执行结果后,返回的各种退出状态。

总结

命令的返回值是其退出状态,退出状态用于检查命令执行的结果(成功/失败)。如果退出状态为0,则命令执行成功。如果命令失败,则退出状态为非零。

相关文章

  • Shell 脚本中的exit状态解释

    命令[https://www.linuxcool.com/]的返回值是其退出状态,退出状态用于检查命令[https...

  • 嵌入式day12

    shell脚本的本质 shell脚本语言是解释型语言 shell脚本的本质:shell命令的有序集合 shell编...

  • Linux中什么是shell?shell有什么用途?

    众所周知,shell既是一门脚本语言,也是一个命令解释器,那么在Linux中什么是shell?什么是shell脚本...

  • shell脚本常用命令-exit 和 if

    1、exit exit 0 退出shell,成功 exit 1 退出shell,失败 exit 2 退出s...

  • 第一个shell

    编写一个shell脚本 shell脚本的开头一定要指定一个shell解释器 给shell脚本加执行权限 执行she...

  • shell语言

    第一个脚本程序 shell脚本文件使用.sh作为文件后缀; 在脚本文件中的第1行使用#!指明shell解释器; 对...

  • Shell脚本编程30分钟入门

    Shell脚本编程30分钟入门 什么是Shell脚本 示例 看个例子吧: 示例解释 第1行:指定脚本解释器,这里是...

  • Lesson-42 Shell(非原创,搬运自 Github)

    Shell脚本编程30分钟入门 什么是Shell脚本 示例 看个例子吧: 示例解释 第1行:指定脚本解释器,这里是...

  • [Linux]Shell

    shell:命令解释器,驱动linux内核;应用程序调用shell命令 1.Shell脚本的执行方式 脚本格式要求...

  • Shell命令的退出状态及错误检查

    退出状态 Shell中执行的每个命令都会通过退出状态码(exit status)来返回命令的执行结果,它是0~25...

网友评论

      本文标题:Shell 脚本中的exit状态解释

      本文链接:https://www.haomeiwen.com/subject/lhlealtx.html