0

I need a bash function that prefixes a date_time string with a string.

show_neb_2017_05_20_16_55

My current function I am hoping would have done this, except that it is requiring a numeric argument.

    function show_neb() {
        a='show_neb_'$(date +"%Y_%m_%d__%H_%M")
        return $a
        }

    echo $(show_neb)

I would have expected it to work, but it isn't. Isn't this just a direct standard output to a string?

1
  • 1
    The point you are missing is return only returns success/failure, not a string. to do what you were attempting, try echo "$a"; return 0; Commented Jun 14, 2017 at 19:20

1 Answer 1

2

return can only be used to provide an integer exit code for the function, not an arbitrary string value. To simulate a return value, you need to write to standard output, then capture that via a command substitution.

show_neb () {
    date +"show_neb_%Y_%m_%d__%H_%M"
    # Replacing echo "show_neb_$(date +"%Y_%m_%d__%H_%M")"
}

val=$(show_neb)

Shell functions really aren't functions in the usual sense; they are more like in-memory shell scripts that are sourced.

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

3 Comments

Just running the function would do what they want.
Yes; I'm emphasizing what you would need if you want to assign the "return value" to a variable.
Making good use of the date output within the function rather than an explicit echo or printf :) (of course in this case, you can get rid of the show_neb function altogether and just use command substitution on the date command itself)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.