Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...