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" = "" ]; 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)) ];
      printf "Fast fail detected. I know about:\n" 


No comments:

Post a Comment