1

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!

Snoopy
  • 41
  • 1
  • 5
  • What doesn't work? What does `createTable` look like? Do you have a function named `function`? `function` is a reserved word in Bash. – Benjamin W. Nov 13 '18 at 19:30
  • The first looks ok unless there are embedded spaces or special chars. Try quotes around the subshell - `variable="$( createTable $table_name )"` – Paul Hodges Nov 13 '18 at 19:33
  • 3
    @PaulHodges `var=$(cmd)` is the same as `var="$(cmd)"`, but `$table_name` should be quoted. – Benjamin W. Nov 13 '18 at 19:43

2 Answers2

4

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.

karakfa
  • 66,216
  • 7
  • 41
  • 56
  • 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? – Snoopy Nov 13 '18 at 19:53
  • The exit status of a function is the exit status of the last command executed by the function. – chepner Nov 13 '18 at 19:54
  • @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. – chepner Nov 13 '18 at 20:20
  • That makes sense! To clarify, you are saying that all of the echo commands within the function are being returned? – Snoopy Nov 13 '18 at 20:31
  • Don't use that terminology. Nothing is returned (except the status). `echo` is send to stdout which you can capture. – karakfa Nov 13 '18 at 20:34
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
chepner
  • 497,756
  • 71
  • 530
  • 681