0

I have written this code to find cube of the number which I am passing while executing this script like: ./my_script.sh 6

The code is working fine till 6 but after 6 it start producing unexpected results. For 7 it should give me cubeof(7) which is 343 but this code gives me 87 for that.

cube () {
        return `expr "$1" \* "$1" \* "$1" `;
}

cube $1;
echo $?;

Some more test cases:

For 8 expected answer should be 512 but it gives 0 same as 9 it gives 217 as results

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 2
    `expr` is an artifact of the 1970s. Shell-builtin math has been part of the POSIX sh standard since 1992; use it. – Charles Duffy Jan 09 '23 at 16:16
  • 1
    That said, the big issue is that `return` is only for exit status, and exit status is a subset of a 16-bit value. It can't be used for arbitrarily large numbers. – Charles Duffy Jan 09 '23 at 16:16
  • 1
    Just emit the result on stdout, exactly like expr does, instead of using return. So `cube() { echo "$(( $1 * $1 * $1 ))"; }`, or to do it the inefficient old-school way, `cube() { expr "$1" "*" "$1" "*" "$1"; }` -- no `return`s needed. – Charles Duffy Jan 09 '23 at 16:17
  • But I also want to store the result in a variable to use it somewhere else in the program – harshkiprofile Jan 09 '23 at 16:20
  • `result=$(cube 8)`, then. – Charles Duffy Jan 09 '23 at 16:20
  • 1
    BTW, using `$(...)` instead of backticks is another thing that's been standardized since the POSIX.2 standard came out in '92; see also https://wiki.bash-hackers.org/scripting/obsolete – Charles Duffy Jan 09 '23 at 16:21
  • Adding to the comment by Charles Duffy: ... and since the upper half of the 16 bit value communicated by `return` usually undergoes a specific interpretation, you can safely use only the lower half, 8 bit. Even there, it is discouraged to use the topmost bit, which leaves you with 7 bit only; and since 126 and 127 have specific meaning too, you better stick to numbers in the range from 0 to 125. See [here](https://linuxconfig.org/list-of-exit-codes-on-linux). Not much arithmetic can be done in this numeric range. – user1934428 Jan 10 '23 at 14:46

0 Answers0