Reputation: 13966
When using the bash builtin "read" to set a variable from user input, is it possible to set that variable as local (in a function), readonly, or use various declare options (e.g. declare -i)?
If not, how do you deal robustly with variables that are read from user input? I'd rather minimize globals that are lying around in my scripts.
Upvotes: 3
Views: 409
Reputation: 158220
If you want to variable to be local you may declare the variable before calling read?:
local input
read input
If it should be an array, read supports the -a
switch:
local arr
read -a arr
<type>foo bar 123
readonly
variable can't be passed to read
. This is because read
will attempt to write the input data to the variable:
readonly foo
read foo
<type> ...
Output:
test.sh: line 2: foo: readonly variable
You could use this workaround: (but check @gniourf_gniourf's comment)
local tmp
read tmp
readonly variable="$tmp"
You might also read into integer vars which have been declared using -i
. Any non numeric input would be interpreted as 0
in this case:
declare -i number
read number
<type>ABC
echo "$number" # 0
declare -i number
read number
<type>123
echo "$number" # 123
Upvotes: 1
Reputation: 75588
You can set the readonly attribute on later time:
local A
read A
readonly A
A=1 ## error
Upvotes: 1