关于bash:shell函数的返回值不能超过255吗?

Could the shell function return value not exceed 255?

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
6
7
8
9
10
11
12
#!/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一样,如何解释呢? 是否有任何功能文档? 我用谷歌搜索了很多没有运气的东西。

谢谢!

更新:

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


如果查看man bash并搜索EXIT STATUS,则会发现以下说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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,如下所示:

1
2
3
4
5
6
#!/usr/bin/env bash
my_function () {
    echo 256
}
retval=$( my_function )
echo $retval