bash

turn off STDERR in a script

exec 2>&-

closing file descriptors

close input file descriptor n

n<&-

close output file descriptor n

n>&-

close STDIN

0<&-, <&-

close STDOUT

1>&-, >&-

close STDERR

2>&-

move files with weird names

To move all files, even with weird special characters in the filename, to another directory do this:

$ find . -print0 | xargs --null mv --target-dir=<DIRECTORY>

Redirect STDERR to STDOUT

command > file 2>&1

Login via ssh using ~/.bashrc

For this to work the file ~/.bash_profile must be modified to enable the line source ~/.bashrc.

Parsing commandline arguments

TEMP=`getopt -o c --long complete -n "$0" -- "$@"`
if [ $? != 0 ]; then
  echo "Syntax error." >&2
  exit 1
fi

eval set -- "$TEMP"

while true; do
  case "${1}" in
    -c|--complete)
      DO_IT_HERE
      ;;
    --)   # finished parsing options
      shift
      break
      ;;
    *)
      echo "Internal error." >&2
      exit 1
      ;;
  esac

  shift
done

extend a path

This piece of code is espcially useful when expanding path information in bash scripts like $PATH or $LD_LIBRARY_PATH:

FOO=${FOO+$FOO:}/usr/local/lib

parameter substitution

Given the variable foo=/tmp/my.dir/filename.tar.gz, we can use these expressions:

  • path=${foo%/*} ⇒ /tmp/my.dir
  • file=${foo##*/} ⇒ filename.tar.gz
  • base = ${file%%.*} ⇒ filename
  • ext = ${file#*.} ⇒ tar.gz

split

To split a string, use this expression:

$ set -- $(IFS=":"; echo ${VARIABLE})

Afterwards, $1, $2, … contain the splitted values.

complete

When the “smart” bash completion gets in your way you can completely remove all functions by

complete -r

To see a short help try

help complete
 
harry/bash.txt · Last modified: 2009/03/27 08:52 (external edit)
Locations of visitors to this page

 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki