Bash Shell Scripting

From Colettapedia
Jump to navigation Jump to search

General

Special Variables

  • $? = the return value of the previous command
  • $! = PID (process ID) of last job run in background
  • $_

Passing Arguments

  • Have immediate access to the first 9 args passed via $0, $1, $2, $3 ... $9
  • $# = the number of arguments passed
  • $$ = Expands to the process ID of the shell.
  • $* = All of the positional parameters, seen as a single word
    • for arg in "$*" # Doesn't work properly if "$*" isn't quoted.
    • "Entire arg list seen as single word."
  • $@ = Same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.
    • for arg in "$@" # $@ sees arguments as separate words.
  • for arg in $* # Unquoted $* sees arguments as separate words.
  • The $@ and $* parameters differ only when between double quotes.
  • shift = $2 becomes $1, $3 becomes $2 etc. Increments the argument pointer.

More Syntax

  • brace expansion {start..end..increment}

Functions

cp -av /camera /local # Keep the file modify times
function rename {
    ORIG_FILE=$1
    PREFIX="SANYO_"
    TOUCH_ARG=`stat -f "%Sm" -t "%Y%m%d%H%M.%S" $ORIG_FILE`
    NAME_TIMESTAMP=`stat -f "%Sm" -t "%Y%m%d_%H%M%S" $ORIG_FILE`
    NEW_NAME="${PREFIX}${NAME_TIMESTAMP}.mp4"
    #echo "Moving $ORIG_FILE to $NEW_NAME"
    mv -v $ORIG_FILE $NEW_NAME
    touch -t $TOUCH_ARG $NEW_NAME
}