0

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 ?

7
  • 1
    You may find the discussion here helpful: Default exit code when process is terminated? Oct 30, 2020 at 1: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.
    – user414777
    Oct 30, 2020 at 1: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.
    – user414777
    Oct 30, 2020 at 1:22
  • I don't know exactly how it's implemented, but if I recall, the exit/return status is an unsigned char. Oct 30, 2020 at 3: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, 2020 at 7:35

1 Answer 1

0

You can use echo:

#!/bin/sh

sum() 
{
 echo 260
}

#main 
TMP=`sum`
echo$TMP
3
  • I would recommend using the $(...) style for command substitutions (as in this comment) since backticks are discouraged by now.
    – AdminBee
    Oct 30, 2020 at 8:31
  • Is there a functional difference? Seems to me that there isn't.
    – D. SM
    Oct 30, 2020 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, 2020 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.