Search code examples
bashshellgrepcut

BASH script help using TOP, GREP and CUT


Use Top command which repeats 5 times, pipe the results to Grep and Cut command to print the PID for init process on your screen.

Hi all, I have my line of code:

top -n 5 | grep "init" | cut -d" " -f3 > topdata

But I cannot see any output to verify that it's working. Also, the next script asks me to use a one line command which shows the total memory used in megabytes. I'm supposed to pipe results from Free to Grep to select or filter the lines with the pattern "Total:" then pipe that result to Cut and display the number representing total memory used. So far:

free -m -t | grep "total:" | cut -c25-30

Also not getting any print return on that one. Any help appreciated.


Solution

  • expanding on my comments:

    1. grep is case sensitive. free says "Total", you grep "total". So no match! Either grep for "Total" or use grep -i.
    2. Instead of cut, I prefer awk when I need to get a number out of a line. You do not know what length the number will be, but you know it will be the first number after Total:. So:

    free -m -t | grep "Total:" | awk '{print $2}'

    1. For your top command, if you have no init process (which you should, but it would probably not show in top), just grep for something else to see if your code works. I used cinnamon (running Mint). The top command is:

    top -n 5 | grep "cinnamon" | awk '{print $1}'

    Replace "cinnamon" by "init" for your requirement. Why $1 in the awk? My top puts the PID in the first column. Adjust accordingly.

    Overall, using cut is good when you have a string that is delimited by some character. Ex. aaa;bbb;ccc, you would cut on -d';'. But here the numbers might have different lengths so using cut is not (IMHO) the best solution.