LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   sh script: problem with return value in function (https://www.linuxquestions.org/questions/linux-software-2/sh-script-problem-with-return-value-in-function-563234/)

jhwilliams 06-20-2007 11:17 AM

sh script: problem with return value in function
 
This script is supposed to return the difference in time between two files,
simulator.o and discretizer.o. Instead, the it prints out a bunch of blank lines. It is as though the function I have defined is not properly returning a value. Any help is greatly appreciated! Thanks, Jameson

Code:

function get_time_diff() {
  disc_time=`stat --format=%Y $file2`
  sim_time=`stat --format=%Y $file1`
  raw_time=`expr $sim_time - $disc_time`

  # in case the files were specifed backwards, make sure time is positive.
  if [ `expr $raw_time` -lt 0 ]; then
    raw_time=`expr 0 - $raw_time`
  fi

  if [ $1="h" ]; then
    return `expr $raw_time / 3600`
  elif [ $1="m" ]; then
    return `expr $raw_time / 60`
  elif [ $1="s" ]; then
    return $raw_time
  else
    return `expr $raw_time / 60`
  fi
}

unit=$1
dir_list=`ls -ad */`

for directory in $dir_list ; do
  if [ -f $directory/simulator.o ]; then
    file1=$directory/simulator.o
    if [ -f $directory/decomposer.o -o -f $directory/discretizer.o ]; then
      if [ -f $directory/decomposer.o ]; then
        file2=$directory/decomposer.o
      elif [ -f $directory/discretizer.o ]; then
        file2=$directory/discretizer.o
      else
        echo "No decomposer.o or discretizer.o found in dir." >&2
      fi
      echo `get_time_diff $unit`
    fi
  else
    echo "No simulator.o found in this dir." >&2
  fi
done


wjevans_7d1@yahoo.co 06-20-2007 11:47 AM

The best way to "return" data from a shell script function is to have that function send the data to standard output, rather than using the bash return statement, because the return code which is sent back by the return statement is a relatively small integer which shows success or failure. Indeed, you show that you expect the result from your function to come via standard output when you say:

Code:

echo `get_time_diff $unit`
The problem is that your function doesn't send its output to standard output; it tries to return that value via the return statement. Instead of this:

Code:

return $raw_time
say

Code:

echo $raw_time
and instead of

Code:

return `expr $raw_time / 60`
say

Code:

expr $raw_time / 60
And so on.

Hope this helps.


All times are GMT -5. The time now is 09:41 AM.