1

Can anyone help me return the correct value from a bash script function?

Here's my function that should return first (and only) line of the file passed as an argument:

LOG_FILE_CREATION_TIME()
{
    return_value=`awk 'NR==1' $1`
    return return_value
}

And here's my call of that function in the other script:

LOG_FILE_CREATION_TIME "logfile"
timestamp=$?
echo "Timestamp = $timestamp"

I always get some random values with this code. If, for example, there's a value of 62772031 in the "logfile", I get

Timestamp = 255

as an output. For some other values in the file, I get other random values as a return value, never the correct one.

Any ideas?

0

3 Answers 3

7

Shell functions work like commands. They can only return errorlevel values (integers). To get strings you can either set a global variable, or print/echo the value and then have the caller use the command substitution (like back-ticks).

This works:

#!/bin/bash

LOG_FILE_CREATION_TIME()
{
    return_value=`awk 'NR==1' $1`
    echo $return_value
}

timestamp=$(LOG_FILE_CREATION_TIME $1)

echo $timestamp

Unrelated, but BTW in Python:

#!/usr/bin/python2

import sys
print open(sys.argv[1]).readline()

;-)

Sign up to request clarification or add additional context in comments.

2 Comments

Really, Python to perform head -1? There will be A LOT of answers if we were to implement it in all languages...
@plundra I'm assuming there will be more to this program than this. Sure, head -1 works best for a one-time thing. I was hinting that the OP might go down a different path than writing a large program with functions in shell.
5

The exit code is limited to 0 - 255, you cannot use it for a timestamp.

Echo your timestamp instead, since you don't seem to be outputing anything else; this ought to be fine?

LOG_FILE_CREATION_TIME()
{
    # If you want to do some more stuff, you might want
    # to use the intermediate variable as you first did.
    awk 'NR==1' $1
}

timestamp=$(LOG_FILE_CREATION_TIME "logfile")
echo "Timestamp = $timestamp"

You might have simplified the function in your example, because if all you wanted was the first line, why not use head -1 logfile instead?

2 Comments

Do you know how could I do this in sh, instead of bash. In sh timestamp=$(LOG_FILE_CREATION_TIME "logfile") doesn't work. It says 'timestamp=$' unexpected
@Eedoh try using backticks, timestamp=`...`
0

Another way is to use a global variable. You can have multiple "return" variables this way. It does not actually return anything, but does the trick.

#!/bin/sh
concat_ret
concat() {
 for s in $*
 do
 concat_ret="$concat_ret $s"
 done
 return 0
}
echo "starting"
concat String1 String2 String3 "and many other strings"
echo $?
echo $concat_ret
exit 0

Output

starting
0
String1 String2 String3 and many other strings

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.