I need to set a default value (y) when the user hits enter in read
validate() {
local validated=false
while [ "$validated" != "true" ]; do
read -p "$1 " $2
$2=${2:-y}
if [[ "$2" == "y" || "$2" == "n" ]]; then
validated=true
fi
done
}
When I run this function with validate "text" test and skip the read with enter, the error test=test: command not found appears.
How can I use the substitution with function arguments?
To write a value to a variable with a dynamic name, you can use printf -v "$name" "$value".
This should be closer to what you want,
though I suspect some further confusion and follow-up questions:
validate() {
local message=$1
local out=$2
local validated=false answer
while [ "$validated" != true ]; do
read -p "$message " answer
answer=${answer:-y}
if [[ "$answer" == "y" || "$answer" == "n" ]]; then
validated=true
fi
done
printf -v "$out" "$answer"
}
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