user435421
user435421

Reputation: 927

Linux function for user prompt

I do not understand why I get this output

Delete content?  aas
Delete content?  a
Delete content?  s
Delete content?  n
ATS=Please enter Y or N.
Please enter Y or N.
Please enter Y or N.

with following script

#!/bin/bash

function prompt2() {
    while true; do
        read -p "$1 " answer
        case $answer in
            [Yy] ) answer=0; break;;
            [Nn] ) answer=1; break;;
            * ) echo "Please enter Y or N.";;
        esac
    done
    return $answer
}

a=$(prompt2 "Delete content? ")
echo "ATS=$a"

I expect that after entering wrong characters I would immediately get line "Please enter Y or N." printed to the screen but it gets printed only after I enter one of expected characters. Also the value that got returned by the prompt function is unexpected.


Thank you all for the explanations! For me (who is used to OOP) this "workflow" is something new.

Upvotes: 1

Views: 70

Answers (3)

tripleee
tripleee

Reputation: 189317

The command substitution captures the function's standard output, not its return code.

The simple non-intrusive fix is to change return to echo inside the function, and to change the diagnostic message to print to standard error (so you don't capture the "Please answer Y or N" text as well).

prompt2() {
    while true; do
        read -p "$1 " answer
        case $answer in
            [Yy] ) answer=0; break;;
            [Nn] ) answer=1; break;;
            * ) echo "Please enter Y or N." >&2;;
        esac
    done
    echo "$answer"
}

I also got rid of the silly Bash-only function keyword for you.

Alternatively, don't change the function, and have the calling code examine the return code.

if prompt2 "Delete things?"; then
    rm -rf /
else
    echo "Wise choice."
fi

Upvotes: 3

jeremysprofile
jeremysprofile

Reputation: 11425

Because that's not how $() works in bash.

a=$(echo 'hi')
echo $a

Will yield 'hi', even though echo, having completed without errors, will return 0.

The return code is stored as $?

prompt2 "Delete content? "
echo "ATS=$?"

will give the answer you want

Upvotes: 1

Lewis M
Lewis M

Reputation: 548

You are close. As @tripleee says, the command substitution is capturing standard out. So, the echo replacing the return is needed.

If you want to see the error message, redirect it to standard out

echo "Please enter Y or N." >&2

Hope this helps

Upvotes: 0

Related Questions