2

Ok so I have a simple script that has the structure down below. I have this sub process that will run for an indefinite amount of time. As of now, it will only stop when the user kills the process manually. I was wondering if there is a way to listen for input from the user without getting stuck on a read line. In other words, while the sub process is running, in the background, see if the user types "quit\n" in the terminal.

...

if [[ option = "3" ]]; then
    while [2 -lt 4]; #THIS IS WHERE I WANT TO CHANGE TO LISTENING FOR INPUT TO QUIT
        #Some sub process that continues to run
    done
fi

....

Thanks for the help! Sorry if this is badly worded, I couldn't think of a better way to describe the issue. As for my brainstorming attempts, I know can just use a variable in the while condition and say do this until it equals "quit", but setting that variable to the input is where I get lost.

1 Answer 1

2

You can run your process in the background (with &) and then run a read from the user in the background as well, and wait for either of them to finish. You end up with something like

mylongrunningcommand &
pid1=$!
echo "enter quit to stop"
while read reply && [ quit != "$reply" ]
do  :
done </dev/stdin &
pid2=$!
wait -n
echo "got quit or command done"
kill -9 $pid1 $pid2
wait

The read is inside a loop so that you can have several tries at typing "quit". It needs to have stdin redirected to it due to the backgrounding. The wait -n returns when either background job finishes, and the kill kills the process ids of both jobs since we don't know which ended.

The above produces some messages from bash about the processes being killed. If you want to suppress these replace the last 2 lines with

exec 3>&2 2>/dev/null
kill -9 $pid1 $pid2
wait
exec 2>&3 3>&-

This temporarily moves stderr to /dev/null.

2
  • This could work! Thanks @meuh! I'll try it out. Do you know if this functionality would work if the sub process is an ssh? Thanks again! Commented Sep 12, 2016 at 12:09
  • You may need to use ssh -n when running the ssh in the background. The ssh command must not expect any input from stdin. Commented Sep 12, 2016 at 12:12

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.