Forin
Forin

Reputation: 1609

Calling function from another function in Bash

I have the following Bash script:

func_1() {
  local arg="$1"
  local var="$(curl $someUrl "$arg")"
  echo "$var"
}

main() {
  # ...
  # some_arg defined
  output="$(func_1 "$some_arg")"

  echo "$output"
}

main

However, after running this script, instead of getting the result of func_1 being assigned to output and then printed, the func_1 is being executed when echoed.

What do I have to modify to execute the function, assign the result and then use the variable in later part of the script?

Upvotes: 1

Views: 308

Answers (1)

Paul Hodges
Paul Hodges

Reputation: 15246

Clarify your testing with some clear indicators.

func_1() {
  local arg="$1"
  local var="$(echo "quoted '$1'")"
  echo "$var"
}

main() {
  local some_arg='this literal'
  output="$(func_1 "$some_arg")"

  echo "[$output]"
}

Now if I run it:

$: set -x; main; set +x;
+ main
+ local 'some_arg=this literal'
++ func_1 'this literal'
++ local 'arg=this literal'
+++ echo 'quoted '\''this literal'\'''
++ local 'var=quoted '\''this literal'\'''
++ echo 'quoted '\''this literal'\'''
+ output='quoted '\''this literal'\'''
+ echo '[quoted '\''this literal'\'']'
[quoted 'this literal']
+ set +x

Seems to be working fine.

Upvotes: 1

Related Questions