Sunday, June 7, 2009

Search for a range of lines


# Use awk's range operator, a comma, to print an entire
# function definition in an init script

awk '/action\(\) {/ , /}/' /etc/init.d/functions

    action() {
      local STRING rc

      STRING=$1
      echo -n "$STRING "
      shift
      "$@" && success $"$STRING" || failure $"$STRING"
      rc=$?
      echo
      return $rc
    }

Thursday, May 21, 2009

Get the directory of the currently running script


# $0 gives the relative path the script was invoked with, so:
#    ./script.sh gives ./script.sh
#    ~/script.sh gives /home/user/script.sh
#
# $(pwd) prints the working directory, not the script file location
#
# `which $0` is a special use to get the full path and name of the script
# Called this way, which does not do its normal search of $PATH
#
# Enclose in double quotes to account for folders with spaces in them

  RUNDIR=$(dirname "$(which "$0")")

Override noclobber


set -o noclobber
echo "test" > test.txt
echo "test" > test.txt 
# bash: test.txt: cannot overwrite existing file

echo "test" >| test.txt

Variable length expansion


# How many characters are in variable XYZ?

  XYZ="12345"
  echo ${#XYZ}

# How many parameters did you feed me?

  function howmany ()
  {
    echo ${#@}
  }

  howmany 1 2 3 4 5 6789

# How many elements are in array XYZ?

  XYZ=( 1 2 3 4 5 6 7)
  echo ${#XYZ[@]}

Tuesday, May 5, 2009

Is this an integer?


function isInteger ()
{
  echo "$@" | grep -q -v "[^-0-9]"
}

if isInteger 1975; then echo "Yes, that is an integer"; fi

Yes, that is an integer

Sunday, May 3, 2009

Instant HTTP Server

Starts a web server on port 8000 and serves up the current directory:

python -m SimpleHTTPServer

Scary? Damn straight.

Get the network ID from an IP address and subnet mask


echo "192.168.5.133 255.255.255.250" | \
awk 'BEGIN {FS="[. ]"; OFS="."} {print and($1,$5), and($2,$6), and($3,$5), and($4,$8)}'

192.168.5.128