Skip to content

Instantly share code, notes, and snippets.

@jameelkaisar
Created June 13, 2022 13:44
Show Gist options
  • Select an option

  • Save jameelkaisar/c94f78033b9ceba41af39c98232fd22e to your computer and use it in GitHub Desktop.

Select an option

Save jameelkaisar/c94f78033b9ceba41af39c98232fd22e to your computer and use it in GitHub Desktop.
Basic Implementation of top Command in Bash

Bash top Command

top.sh

echo " $(printf '%0.1s' "-"{1..50})";
echo -n " ";
echo -n "$(printf '%-10s' PID)";
echo -n "$(printf '%-10s' USER)";
echo -n "$(printf '%-15s' COMMAND)";
echo -n "$(printf '%-15s' MEMORY)";
echo;
echo " $(printf '%0.1s' "-"{1..50})";
for i in $(printf -- '%s\n' `ls /proc` | egrep "^[[:digit:]]+$");
	do if test -f "/proc/${i}/comm";
		then echo -n " ";
		echo -n "$(printf '%-10s' ${i})";
		echo -n "$(printf '%-10s' $(ls -l /proc/${i}/comm | cut -d ' ' -f 4))";
		echo -n "$(printf '%-15s' $(cat /proc/${i}/comm))";
		echo -n "$(printf '%-15s' "$(cat /proc/${i}/status | egrep "VmRSS" | cut -f 2-)")";
		echo;
	fi;
done;
echo " $(printf '%0.1s' "-"{1..50})";

Output

ajmi@burner:~$ source top.sh
 --------------------------------------------------
 PID       USER      COMMAND        MEMORY
 --------------------------------------------------
 1         root      init               1084 kB
 1719      root      init                 72 kB
 1720      root      init                 80 kB
 1721      ajmi      bash               5900 kB
 25529     root      init                 72 kB
 25530     root      init                 80 kB
 25531     ajmi      bash               5708 kB
 8458      root      init                 72 kB
 8459      root      init                 80 kB
 8460      ajmi      bash               5260 kB
 8473      root      su                 4084 kB
 8474      khan      bash               5264 kB
 8486      khan      sleep               576 kB
 --------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment