Home > Blockchain >  bash : evaluate function return value with spaces in arguments
bash : evaluate function return value with spaces in arguments

Time:01-14

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:

CodePudding user response:

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)"

CodePudding user response:

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]}"
  •  Tags:  
  • bash
  • Related