21

According to this answer: https://stackoverflow.com/a/1952480/582917

I can read in and therefore assign multiple variables.

However I want those variables to be local to a bash function so it doesn't pollute the global scope.

Is there a way to do something like:

func () {
    local read a b <<< $(echo 123 435)
    echo $a
}
func
echo $a

The above doesn't work. What is a good way of reading into local variables?

2 Answers 2

32

You were almost there: you just have to define the variables as local, but beforehand instead of in the read declaration:

func () {
     local a b
     read a b <<< $(echo 123 435)
     echo $a
}

Test

$ func 
123
$ echo $a
$
Sign up to request clarification or add additional context in comments.

Comments

6

Just declare the variables to be local on one line, and use them on a separate line:

$ a=5
$ func() {
    local a b
    read a b <<< "foo bar"
    echo $a
}
$ func
foo
$ echo $a
5

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.