Bash shell scripting

From Andreida
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Links

Parameters

   $$ PID of the process
   $? exit status
   $0 call of the current script
   $1 1st parameter
   $2 2nd parameter
   $n etc...
   $* all parameters
   $# parameter count

|| and && - status based commands

Syntax:

 normal-command && if-succeeded || if-error

Example:

 rm /bla  && echo ok || echo not ok;echo Done

Will normally output:

 rm: cannot remove `/bla': No such file or directory
 not ok
 Done

Attention:

 rm /bla && echo ok ; echo really ok || echo not ok ; echo shit

Will output

 rm: cannot remove `/bla': No such file or directory
 really ok
 shit

So || and && will only work for the last command and will only work for the next command.

While on console

while true; do echo -n `date`;ls -l <file>; sleep 1; done;

parameter check

if [ "$1" = "--help" ] || [ $# -ne 1 ]; then
    echo my script v 0.1, it's me !
    echo This script will do some cool stuff but I won't tell you what.
    echo Syntax: $0 \<file\> \<whatever\>
    exit 1
fi

do something depending on output/no output of a command

#!/bin/bash
for file in ~/work/Sx*
    do
        cd $file
        out=$(cvsupdate)
        if [ "$out" != "" ]; then
            pwd
            echo "$out"
        fi
done    

Use the double quote for the echo or you will lose all line breaks.

get the absolute directory of the executing script

#!/bin/bash
DIR=$(cd `dirname $0` && pwd)
echo $DIR

Remove the first/last character

First character:

echo super | sed 's/^.//'

Last character:

echo super | sed 's/.$//'