Jonny Nguyen
Jonny Nguyen

Reputation: 43

read -p inside the function in bash script

I am trying to write the function including read -p, however, for some reason the read -p always show first before other command, although other commands are before read -p. Here is my code:

function try {
    temp=10
    echo "$temp"
    while [[ $temp -gt 0 ]]
    do
        read -p  "what num do you want?" num
        echo "$num"
        temp=$((temp -  num))
        echo $temp
    done
}
run=`try`
echo "$run"

As the above code, I expected to see value of temp before statement "what num do you want?". However, here what I got:

what num do you want?5
what num do you want?5
10
5
5
5
0

Can anyone help me to solve my problem. Thanks in advance

Upvotes: 1

Views: 575

Answers (1)

Cyrus
Cyrus

Reputation: 88999

Duplicate each line in your function which contains echo and append >&2 to the new lines to redirect stdout to stderr.

Upvotes: 1

Related Questions