Showing posts with label regex. Show all posts
Showing posts with label regex. Show all posts

Wednesday, 1 December 2010

Bash if statement + RegEx + String matching

After going slowly crazy trying to remember how an if statement is formed in shell with its lovely and entirely useless help messages.

 I've decided to post this: #!/bin/sh FULLHOSTNAME=`hostname -f` if [ "$FULLHOSTNAME" = "loneqflocfd0025.uk.db.com" ]; then echo "hi" fi 

  Notes: You need a space after '[' and before ']' You need a ';' ...and while I'm here - here is how to do a regex if:

  if [[ "los" =~ lo.* ]]; then 

  ...String matching with variables When comparing strings " is very different to ' ' will not evaluate variables " will evaluate them 

Hence: fish=haddock echo 'Hello $fish'=== Hello $fish echo "Hello $fish" === Hello haddock 

 

Using dates and comparing current time with something that may have taken less than 2 seconds:

  start=`date +%s`

  # Do something

  now=`date +%s`

   if [ $start -gt $((now - 2)) ];
   then
      printf "Fast fail detected. I know about:\n" 

   fi


Thursday, 13 May 2010

Disk usage tools

So we all know:

df -kH
du -h --max-depth=1

How about if we wanted to look only 2 directories 'down' and only list directories at least 10M in size?

du -h --max-depth=2 | egrep "^([0-9]{2,3}M)|^([0-9]\.?[0-9]*G)"

RegEx breakdown:
Because of the ^ this only filters on the start of the line.
[0-9]{2,3}M <- 2="" 3="" br="" by="" digits="" followed="" m="" or="">[0-9]\.?[0-9]*G <- 0="" 1="" br="" by="" digit="" digits="" followed="" g="" many="" optional="" to="">
....and now du by size:

du -Psckx * | sort -nr
why not add this as an ailias to your .bashrc ?
alias dus='du -Psckx * | sort -nr'


<- 2="" 3="" br="" by="" digits="" followed="" m="" or=""><- 0="" 1="" br="" by="" digit="" digits="" followed="" g="" many="" optional="" to="">If df and du don't line up (they operate in different ways) one of the reasons could be that processes are holding handles to deleted files.
<- 2="" 3="" br="" by="" digits="" followed="" m="" or=""><- 0="" 1="" br="" by="" digit="" digits="" followed="" g="" many="" optional="" to="">Find processes still clinging on to open file handles:
<- 2="" 3="" br="" by="" digits="" followed="" m="" or=""><- 0="" 1="" br="" by="" digit="" digits="" followed="" g="" many="" optional="" to="">lsof  +L1