Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Read into multiple local scope variables

Tags:

bash

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?

like image 339
CMCDragonkai Avatar asked Jun 02 '14 09:06

CMCDragonkai


2 Answers

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
$
like image 105
fedorqui 'SO stop harming' Avatar answered Oct 16 '22 19:10

fedorqui 'SO stop harming'


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
like image 34
glenn jackman Avatar answered Oct 16 '22 21:10

glenn jackman