Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Both Pass an Argument Into a Function and Get a Return Value in Bash? [duplicate]

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!

like image 582
Snoopy Avatar asked Sep 15 '25 09:09

Snoopy


1 Answers

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.

like image 182
karakfa Avatar answered Sep 17 '25 01:09

karakfa