0

I have:

func() {
        echo a "b c"
}

set $(func)

echo 1: $1
echo 2: $2
echo 3: $3

I want to get two arguments: "a" and "b c". How should func() echo to achieve that?

Tried as above. Getting

1: a
2: b
3: c

I want

1: a
2: b c
3:
1
  • 4
    Well, the output of func is a b c, so how would you know which letters are to be grouped together? Commented Jan 14, 2023 at 11:17

4 Answers 4

2

How should func() echo to achieve that?

It is not possible to do that. No matter the content of func(), it's impossible with set $(func) to achieve that.

Prefer:

func() {
    array=(a "b c")
}
func
set -- "${array[@]}"

Do not use, because eval is evil:

func() {
    printf "%q " a "b c"
}
eval "set -- $(func)"
Sign up to request clarification or add additional context in comments.

3 Comments

IMHO array is local to func() and not available after func() finishes.
I disagree. There is no local in the function. array is not local and the code works as presented completely fine. In Bash, variables have global (process) scope, unless declared with local or declare in a function.
This surprises me, but you are right.
2

Bash's mapfile can be used to read a stream of null-delimited values output from a function into an array.

Applied to question:

#!/usr/bin/env bash

func() {
  printf '%s\0' a "b c"
}

mapfile -d '' arr < <(func)

echo 1: "${arr[0]}"
echo 2: "${arr[1]}"
echo 3: "${arr[2]}"

Comments

0

I do not like the array variant, it looks too complicated. But I was able to restructure my code, avoiding this problem.

Comments

0

2 mistakes:
You forgot to escape the quotes, so your output is:

 $ echo a "b c"
 a b c

What you want is:

 $ echo a \"b c\"
 a "b c"

And you have to evaluate the response:

eval set $(func)

That's all

2 Comments

Does not work for me. The result are still three arguments. func() { echo a "b c" } eval set $(func) echo 1: $1 echo 2: $2 echo 3: $3
Your comment seems to suggest that you forgot the back slashes in the function. They are essential. So func() { echo a \"b c\" }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.