简体   繁体   中英

Read the last line of output of a bash command

I want to read the current line of output from a bash command. I know I could get this with cmd | tail -1 cmd | tail -1 , but I want to run this as a seperate command (tint2 executable) as a sort of progress meter.

For example:

I have a python program that outputs Downloaded x out of y as it downloads images, and I want to get the output as a shell variable.

Or:

Maybe I'm running pacman -Syy and I want

extra 420.6 KiB 139K/s 00:09 [#####-----------------] 24%

Is this possible?

Edit: Something is running in the terminal. I want a command that outputs the last output of the command in the previous terminal, maybe inputting a pid.

You can use tee to write things to the terminal and some logfile.
Lets say your python program looks like this

function mypython {
   for i in 10 30 40 50 80 90 120 150 160 180 190 200; do
      (( progress = (100 * i + 50) / 200 ))
      printf "extra   xx Kb, total %-3d of 200 (%d %%)\n" $i ${progress}
      sleep 1
   done
}

You can redirect or tee the output to a tmp file: (mypython > /tmp/robert.out) & or (mypython | tee /tmp/robert.out) &

In another window you can get the last line with tail -1 /tmp/robert.out

When you only want to see a progress, you might want something like to get the last line to overwrite the previous one.

mypython | while read -r line; do
   printf "Progress of mypython: %s\r" "${line}"
done

When this is what you want you might want to change your python program

  printf "...\r" ... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM