4

My code is very simple.

variable=$( createTable $table_name ) 

or

returnedVariable=$( function $argument ) 

My code breaks on this line. I haven't been able to find anywhere on the internet how to both pass an argument and get a return value in Bash.

UPDATE: I get it now. I can't have multiple echo's in my function. Also echo should never be considered a return but a print statement or stdout which you can capture. Thank you for the feedback!

4
  • What doesn't work? What does createTable look like? Do you have a function named function? function is a reserved word in Bash. Commented Nov 13, 2018 at 19:30
  • The first looks ok unless there are embedded spaces or special chars. Try quotes around the subshell - variable="$( createTable $table_name )" Commented Nov 13, 2018 at 19:33
  • 3
    @PaulHodges var=$(cmd) is the same as var="$(cmd)", but $table_name should be quoted. Commented Nov 13, 2018 at 19:43
  • I don't see how this is a duplicate of stackoverflow.com/questions/613572/…. Commented Jan 30 at 22:50

2 Answers 2

8

is this what you're trying to do?

$ function createTable() { echo "this is the table: $1"; } $ var=$(createTable "$table_name") $ echo "$var" this is the table: New Table 

note that there is nothing returned from the function, that's reserved for the success/error status. Here will default to zero. The conceptual "function return value" is through the stdout. These are not "functions" in mathematical sense.

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

5 Comments

Yes! That is it! I think it may be that one can't have multiple "echo"s in a function. Is the last echo treated as a return or the first echo the function comes across?
The exit status of a function is the exit status of the last command executed by the function.
@Snoopy You seem to be talking about output, not a return value. The output of all the echo commands produces the output of the function.
That makes sense! To clarify, you are saying that all of the echo commands within the function are being returned?
Don't use that terminology. Nothing is returned (except the status). echo is send to stdout which you can capture.
1

In this case, the exit status of the assignment is the exit status of the command substitution.

$ var=$(echo "hi"; exit 3) $ rv=$? $ echo "$var" hi $ echo "$rv" 3 

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.