Step1. Start the command below

# COMMAND 1 Use this command  if you have "watch"
# ** use this as most likely you do have watch **

watch -n0.2 'ps uxeww | egrep "btrfs fi defrag|%CPU" | egrep -v "watch|awk|grep|sh"; ls -lisah /proc/$(ps ax | grep "btrfs fi defrag" | egrep -v "watch|awk|grep|sh" | awk "{print \$1}" 2> /dev/null)/fd/ 2> /dev/null;'

# COMMAND 2: Use this command if you dont have "watch", and you only have while (notice change awk to single quotes and removed back slash), awk is best run with single quotes (but in reality it probably doesnt matter if you run with double quotes as long as you watch out for correct escapes with backslash)

while true; do clear; ps uxeww | egrep "btrfs fi defrag|%CPU" | egrep -v "watch|awk|grep|sh"; ls -lisah /proc/$(ps ax | grep "btrfs fi defrag" | egrep -v "watch|awk|grep|sh" | awk '{print $1}' 2> /dev/null)/fd/ 2> /dev/null; done;

NOTE: replace btrfs fi defrag  with btrfs f.* de.*  if you run btrfs fi defrag using its shorter name like btrfs f de, which also works because btrfs command is like the cisco interface and takes shorter commands (as long as they are none-ambigous, meaning other similar ones dont exist – for example we can not use btrfs f d because there is btrfs filesystem defrag and btrfs filesystem df, both “defrag” and “df” begin with “d”)

DETAILS: What the command does: The command below runs ps uxeww which lists all of the processes and their stats (including the command & environment variables – env vars are listed right after the command and its arguments), but it only shows the header and the “defrag” command. After that it finds the process id of the “btrfs fi defrag” command and it lists with a verbose “ls” all of its associated file descriptor folder content /proc/<pid>/fd. The /proc/<pid>/fd folder is where linux keeps track of what files a process has open (each process has this fd folder to keep track of all files being read or written). The btrfs defrag process will of course at any moment in time have the listing of the current files & folders its working on defraging in the /proc/<pid>/fd folder – because it has to read and write those files. This “ps uxeww” and “ls -lisah” command is repeated over and over (0.2 second interval) with a “watch” (it could have been done with a while loop & clear screen command, however watch doesn’t have the annoying blink so its better on the eyes). The watch can include several commands if you use single quotes, on the inside I had to use double quotes. Awk usually takes in single quotes, but I used double quotes, and just used backslash on the $1 (so its \$1) so it didn’t error out due to the use of the double quotes in awk. Also note that when there is no defrag running all you see is the “ps” header: “USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND


Step2. Start the defragmentation / defrag process

Leave a Reply

Your email address will not be published. Required fields are marked *