Linux 4 All

Best Linux tricks source

Posts in the shellscript category

Here is a little curl magic to get you how long it it will take to connect to a site. It will display time to connect, time to namelookup, time to first byte and so on.

curl -s -w "\ntime connect: %{time_connect}\ntime namelookup: %{time_namelookup}\ntime pretransfer: %{time_pretransfer}\ntime redirect: %{time_redirect}\ntime to first byte: %{time_starttransfer}\ntime total: %{time_total}\nhttp code: %{http_code}\n\n" -o /dev/null http://linux4all.uk

time connect: 0.165
time namelookup: 0.133
time pretransfer: 0.166
time redirect: 0.000
time to first byte: 0.392
time total: 0.432
http code: 200

Some time ago I had to deal with a request to delete all but the newest 50 files from a folder. To make my life a little bit miserable, there were other folders inside that folder which shouldn’t be deleted and obviously some files with space in their names

In the end I did a small script taking the folder as first parameter and number of files to keep as the second one.

#!/bin/bash
if [ $# -eq 0 ]
 then
  echo " This script will delete all but newest files from a specified folder."
  echo ""
  echo " Usage: source $0  "
  exit 1
fi

TOTAL_FILES=$(find $1 -maxdepth 1 -type f -print0| xargs -0 ls -lt | wc -l)
FILES_TO_DELETE=$(echo "$TOTAL_FILES-$2" | bc)

find $1 -maxdepth 1 -type f -print0 | xargs -0 ls -t | tail -$FILES_TO_DELETE | sed -e 's/ /\\ /g' | xargs rm

The following one-liner will display number of Apache PIDs and sort them after memory usage:

ps aux | awk '$11 ~ /httpd/ {c++; SUM +=$6; print $6/1024" MB, PID:", $2|"sort -rn| head"} END {print c" Total Apache Processes"} END {print SUM/1024" MB Total Memory"} END {print "Top 10 Memory users:"}'

This is a small shell script to get all files greater than 100M starting from “/”. Replace SIZE and FS values to fit your needs.

SIZE=100M; FS='/'; find $FS -size +$SIZE -exec du -hs {} \; 2>/dev/null | sort -nrk 1,2