Bash: Preventing Bias Contiguous Forwarding Function Errors

Want to get user 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 you enter the error value first, and here are the results:

input y/n: other
input y/n: y
val is: Please answer y or n.
y

      

Thank.

+3


source to share


2 answers


Change your error to stderr (FD 2), not stdout (default, FD 1):



echo "Please answer y or n." >&2

      

+5


source


Better to use a shared global variable to pass values ​​between the function and the caller. This is more efficient than calling 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"

      

+3


source







All Articles