1

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?

7
  • Change output="$(func_1 "$some_arg")" to output=$(func_1 "$some_arg"). Your quotes are all messed up. They do not nest. Commented Jul 13, 2021 at 13:53
  • @Jack still same issue. Commented Jul 13, 2021 at 13:55
  • 1
    @Jack, they aren't nested - inside those parens is a whole different subshell. The syntax is valid. Try echo "$( echo "date;date" )" vs echo "$( echo date;date )". Commented Jul 13, 2021 at 13:59
  • 1
    Try output="$(func_1 "$some_arg" 2>&1)". What output is beeing outputted from func_1? Commented Jul 13, 2021 at 14:02
  • @Forin So how do you know that func_1 is not being executed? I put in some echo directing output to /dev/stderr, and it all executed as written. Commented Jul 13, 2021 at 15:01

1 Answer 1

1

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.

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

1 Comment

Worked for me, too. I don't see a problem.

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.