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?
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
}
$ func
123
$ echo $a
$
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With