Reputation: 1299
Want to get user's input from a function. However, the prompt ("Please answer y or n." in this case) is also included in the return value.
#!/bin/bash
input() {
while true; do
read -p "input y/n: " yn
case $yn in
[Yy]* ) yn="y"; break;;
[Nn]* ) yn="n"; break;;
* ) echo "Please answer y or n.";;
esac
done
echo $yn
}
val=$(input)
echo "val is: $val"
If input an error value first and here is the results:
input y/n: other
input y/n: y
val is: Please answer y or n.
y
Thanks.
Upvotes: 3
Views: 44
Reputation: 75478
Better use a common global variable to pass values between the function and the caller. It's more efficient than summoning subshells with command substitution.
#!/bin/bash
input() {
while true; do
read -p "input y/n: " __
case "$__" in
[Yy]* ) __="y"; break;;
[Nn]* ) __="n"; break;;
* ) echo "Please answer y or n.";;
esac
done
}
input; val=$__
echo "val is: $val"
Upvotes: 3
Reputation: 295373
Echo your error to stderr (FD 2), not stdout (the default, FD 1):
echo "Please answer y or n." >&2
Upvotes: 5