-1

Assuming I have this shell program :

foo.sh

#!/bin/sh

sum() { return 260 }

#main sum TMP=$? echo$TMP return $TMP

When running echo $? I get only the first 8 bits of the returned number 260 : 100000100 => 00000100 => 4 . Is there any explanation for this ? Does this mean that my ubuntu supports only 8 bits ?

Samir
  • 133
  • 1
    You may find the discussion here helpful: Default exit code when process is terminated? – steeldriver Oct 30 '20 at 01:19
  • 1
    Yes, only 8 bits are supported in the return value / exit status. And only two kind of values really matter: 0 and non-0. –  Oct 30 '20 at 01:19
  • 3
    If you want to "return" data from a function, you do it by writing to some file descriptor, like the default 1 = stdout, and then capture it via command substitution: sum(){ echo 260; }; tmp=$(sum); echo $tmp. Yes, this is much more awkward than in languages like C or Perl. –  Oct 30 '20 at 01:22
  • I don't know exactly how it's implemented, but if I recall, the exit/return status is an unsigned char. – glenn jackman Oct 30 '20 at 03:36
  • @user414777 No, 32 bits are supported as exit code on UNIX since 1988.You just need to use waitid() instead of the historical wait() in order to collect all available information for the child. You can do this by using a modern shell like the recent Bourne Shell (bosh) if you are on a POSIX compliant operating system. – schily Oct 30 '20 at 07:35
  • @schily While it's true that waitid(2) allows to retrieve the full exit status on Solaris, it does NOT on Linux, and no shell besides bosh is using it, anyways. Also, bosh is not installed by default on any system I know of. (I'm taking your word for bosh, I haven't yet tested it ;-)). –  Oct 30 '20 at 21:05
  • @user414777 waitid() works correctly on Solaris, UnixWare, FreeBSD, NetBSD and probably other OS. If other shells are on a state from the mid-1980s, this may cause a re-think about these shells. If Linux is not willing to fix kernel bugs, this should cause people users to re-think whether it is a good idea to use it. – schily Oct 30 '20 at 21:46

1 Answers1

0

You can use echo:

#!/bin/sh

sum() { echo 260 }

#main TMP=sum echo$TMP

D. SM
  • 191
  • 1
  • 10
  • I would recommend using the $(...) style for command substitutions (as in this comment) since backticks are discouraged by now. – AdminBee Oct 30 '20 at 08:31
  • Is there a functional difference? Seems to me that there isn't. – D. SM Oct 30 '20 at 14:30
  • At first look, and in simple cases, no. But when you start quoting (as is usually recommended to prevent unwanted word-splitting) shell variables and command substitutions which themselves use shell variables, or when you want to nest command substitutions, the difference will become obvious. The Q&A I linked should give some insight (or point to sources that do). – AdminBee Oct 30 '20 at 14:36