PG Tips

From RĂ¼diger Kuhlmann:

Tips for inexperienced shell coders:

  • cut -b x-y can almost always replaced by the bash ${variable:x:d} feature.
  • cut -c x-y - think whether you actually meant cut -b.
  • ${#var} gives the length in bytes (not characters) of $var.
  • ${var#*B} gives var without the string up to the first B (B any string), thus, equivalent to cut -f2 -d"B" if B is only one byte long and we're looking at one line only
  • ${var%%B*} gives var up to before the first string B, thus, equivalent to cut -f1 -d"B" if B is only one byte long and we're looking at one line only
  • don't tell date to output what you want to cut away (d'uh)

If-statements

If you want to check if a function or command succeded or not, you could do it like this:

if [ $(somecommand ; echo $?) -eq 0 ]; then
   echo "success"
...

The following will do the exact same thing though, but save you a couple of system calls:

if somefunction ; then
    echo "success"
...

To negate an expression, just prepend the ! sign:

if ! somefunction ; then
   echo "not success"
...