Thursday, April 09, 2009

Bash

Bourne Again Shell

1. File operations

if [ -e "filename" ]; : -> exists
r -> readable, w -> writable, h -> link, -x executable,

PROGRAM_NAME= $0
basename = `basename $PROGRAM_NAME`

Appending to a file:
cat "At the end" >> $filename

Prepending to a file:
cat "At the beginning" > $tempfile
cat $filename >> $tempfile
cat $tempfile > $filename


for file in `ls $PWD`
do
echo $file
done

if [ ! -f "/var/opt/myfile.txt" ]; then
mkdir -p "/var/opt"
cat $content >> /var/opt/myfile.txt
fi

2. String operations
if [ -n "$var" ]; to check whether var is null
if [ -z "$var" ]; to check whether var is empty
if [ -z "$var" ]; then
:
else
echo ok var is not null
fi

3. Arithmetic expressions
(( a=$a+1 ))
(( ++$a ))
a=`$a + 1`
count=0
while [ $count <>
do
echo "Type your name 10 times"
done
4. Logical operations
if [ ! $a ]
if [ $a -ne 0 ]
if [ $a -gt 20 ]
if [ $a -a $b ]
if [ $a -o $b ]
[ -z "$a" ] && exit 0

4. functions:
exit 0 is success, non-zero exit is failure
status is checked by $?
if [ $? = 0 ] -> success
Call by value mechanism (Use \ for referencing )
arguments count $#
arguments: $@ or $*
shift operator
while


5. Execution modes of shell scripts

set -x ... set +x will enable tracing

sh -x script.sh

set -o errexit

set -e -> Froces shell to quit if a command fails. With out, a program has to be written this way

command

if [ $? <> 0 ]; then

echo blah blah command failed

exit 1

fi

with set -e, the result checking is automatically enforced. The script exits when the command fails

set -e

....

comand

But some commands may be interspersed with important commands, that we really donot care of.

In such cases, automatic exit under set -e can be escaped by using the idiom

dontcarecommand true

dontcarecommand { echo command failed! ; exit 1 }

Or if a block of code node needs to be ignored

set +e

block of code

set -e

Some commands inherently possess this option. When executed under -e mode, the -f option of rm will remian silent if the file does not exist.

set -u :-> enforces the program to exit when an undeclared variable is encountered in the script

set -u; rmdir $TMP/etc/hosts -> Will exit if $TMP is not declared




5. Regular Expressions

6. Some sed commands:

7. Some awk commands


id -nu -> username
[ $UID = 0 ] -> root
$$ -> current process id
tr '[:lower:]' '[:upper:]' -> lowerToUpper
IFS -> Internal Field Separator (defaults to space)
set $IFS=':'
read -t 4 name; SECONDS -> number of seconds passed
$LINENO -> Line number with in the script, usefule for debug statements
echo $FUNCNAME -> current function name
SHLVL->Shell Level
function f()
{
local k
while [ $# -ne 0 ];
do
k=$1$k
shift
done
return $k
}
while read line
do
echo eval f $line
done

No comments: