【问题标题】:Could the shell function return value not exceed 255? [duplicate]shell函数返回值不能超过255吗? [复制]
【发布时间】:2019-06-02 18:33:42
【问题描述】:
#!/usr/bin/env bash
# set -x

readonly err_code=256

my_function () {
    return $err_code
}

my_function

echo $? # print 0

如果err_code超过255,所有的最高位都会像unsigned byte一样被丢弃,这怎么解释?有没有这方面的功能文档?我在 Google 上搜索了很多,但运气不佳。

谢谢!

更新:

好的,我明白了,它不仅发生在 shell 中,而且发生在基于 Unix 的系统中,shell 函数也被命令替换调用。 感谢您提供相关问题!

【问题讨论】:

  • 它不仅发生在 shell 中,而且发生在基于 Unix 的系统中 - 不,你误会了。单字节限制是 UNIX 系统上的 process 退出状态,正确。 function 的返回值仅作为单个字节是 shell 的一个特性。 UNIX(或其他地方)上的大多数语言都允许从内部函数返回其他对象类型。
  • @cdarke 我明白了,python 和 javascript 不包括在内。
  • 不仅仅是python 和 javascript、C、C++、perl、ruby、C#、Java,都可以有函数/方法/子例程返回更复杂的对象,而不仅仅是一个字节。但是除了 UNIX 上的无符号字节之外,他们都不能以任何方式退出他们的进程。顺便说一句,在 Windows 上,进程可以以 32 位 int 退出,这可能会导致可移植性问题。

标签: bash macos function shell return


【解决方案1】:

如果您查看man bash 并搜索EXIT STATUS,您会发现以下解释:

EXIT STATUS
   The  exit  status  of  an  executed command is the value returned by the waitpid system call or equivalent
   function.  Exit statuses fall between 0 and 255, though, as explained below,  the  shell  may  use  values
   above  125  specially.   Exit  statuses from shell builtins and compound commands are also limited to this
   range.  Under certain circumstances, the shell will use special values to indicate specific failure modes.

   For the shell's purposes, a command which exits with a zero exit status has succeeded.  An exit status  of
   zero  indicates  success.  A non-zero exit status indicates failure.  When a command terminates on a fatal
   signal N, bash uses the value of 128+N as the exit status.

   If a command is not found, the child process created to execute it returns a status of 127.  If a  command
   is found but is not executable, the return status is 126.

   If  a  command  fails because of an error during expansion or redirection, the exit status is greater than
   zero.

   Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error  occurs
   while  they  execute.   All  builtins  return  an  exit status of 2 to indicate incorrect usage, generally
   invalid options or missing arguments.

   Bash itself returns the exit status of the last command executed, unless a syntax error occurs,  in  which
   case it exits with a non-zero value.  See also the exit builtin command below.

如果您真的想要返回大于 125 的值,可以使用 echo 而不是 return,如下所示:

#!/usr/bin/env bash
my_function () {
    echo 256
}
retval=$( my_function )
echo $retval

【讨论】:

  • 这很有帮助,谢谢!所以自定义的错误码范围应该在1..126以内吧?
  • 1..125。很高兴为您提供帮助!
  • echo 替换return 不是一个好主意,因为我的函数中有其他echo,无论如何,谢谢!
猜你喜欢
  • 2016-07-18
  • 1970-01-01
  • 2013-12-11
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多