user2847598
user2847598

Reputation: 1299

bash: preventing a redirected function's errors from mixing with output

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

Answers (2)

konsolebox
konsolebox

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

Charles Duffy
Charles Duffy

Reputation: 295373

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

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

Upvotes: 5

Related Questions