3

I have this very simple script:

#!/bin/bash

read local _test
echo "_test: $_test"

This is the output.

$ ./jltest.sh
sdfsdfs
_test: 

I want the variable _test to be local only. Is this possible?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
mrjayviper
  • 1,971
  • 3
  • 25
  • 41

1 Answers1

2

The local builtin only works inside a function. Any variable you set in your script will already be "local" to the script though unless you explicitly export it. So if you remove that it will work as expected:

#!/bin/bash

read _test
echo "_test: $_test"

Or you could make it a function:

my_read () {
  local _test
  read _test
  echo "_test: $_test"
}

Even inside the function the local builtin wouldn't work in the way you have written it:


Your code is actually setting a variable literally named local:

#!/bin/bash

read local _test
echo "_test: $_test"
echo "local: $local"

$ ./script.sh
sssss aaaaa
_test: aaaaa
local: sssss
jesse_b
  • 35,934
  • 12
  • 91
  • 140