1

Assuming the following dummy command in bash:

### dummy long_operation_cmd function, for easy reproduction:
function long_operation_cmd() {
  echo "operation 1"
  sleep 5
  echo "operation 2"
}

I am currently running a bash script in the following way:

{
    long_operation_cmd
    echo '===ALL DONE==='
} > /tmp/logfile.tmp &
tail -f /tmp/logfile.tmp | sed '/^===ALL DONE===$/ q' \
&& rm /tmp/logfile.tmp

This allows me run the long operation safely in the background, track the output, and make sure Ctrl+C doesn't break the execution.

Most importantly, when the operation is done, sed gets me out of the follow mode.

I want to replace tail -f with less +F, and this is what I came up with:

{
    long_operation_cmd
    echo '===ALL DONE==='
} > /tmp/logfile.tmp &
less +F -- /tmp/logfile.tmp \
&& rm /tmp/logfile.tmp

However, I can't figure a way to break out of the follow mode automatically when the ===ALL DONE=== pattern is reached (or when the long_operation_cmd operation is done).

Any suggestions on solving this?

2 Answers 2

0

You could send the process a SIGINT signal when "ALL DONE":

kill -int PID

which, though, would require you to know the PID (run less +F in background as well?).

1
  • Maybe I can run another background worker to terminate less, but less needs to be run on the foreground. Thanks for the suggestion though.
    – Lockszmith
    Commented Jul 11, 2022 at 18:39
0

Looks like I'll take a different path.

I'll tail -f first, trap the Ctrl-C, and less afterwards. If all is well, I won't run less, but if tail 'fails' (which is the case of Ctrl+C being used), I'll launch less - I could then continue with 'F' from within less, if needed.

The end result will look like this:

{
    long_operation_cmd
    echo '===ALL DONE==='
} > /tmp/logfile.tmp &
(trap : INT; tail -f /tmp/logfile.tmp | sed '/^===ALL DONE===$/ q' ) \
|| less +G /tmp/logfile.tmp && rm /tmp/logfile.tmp

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .