Aug 27, 2010

Bash Programming

Write,

#!/bin/bash
echo Hello World
In a file and save it as script.sh

Then type
$chmode 777 script.sh
{To make it as an excecutable}

now type
$./sript.sh
to run the script
You will see the output as
$Hello World

It is a basic bash shell script.

There are 3 file descriptors
stdin <0 (<) stsout 1> (>)
stderr 2>
(std=standard)

By using fle descriptors we can do,

1. Redirect stdout to a file
eg:- ls -la > fileNmae.txt
This will not print the result of the "ls -la" command but will store in the file "fieName.txt"

2. Redirect stdout to a file
eg: grep da * 2> error_log.txt
This will store data if there is any error only.

3. Redirect stderr to stdout
eg: grep da * 2>&1

4. Redirect stdout to stderr
eg: grep da * 1>&2

5. redirect stdout and stderr
eg: grep &> out_error.txt

Pipe (|)
Send a output of a processer as an input to another processer.
eg: ls -la | less

Variables

#!/bin/bash
SRT='Hello World'
echo $SRT

This is a basic bash script which use variables. Variable is SRT and to get the stored data it use "$" sign infront of the variable.

We can create local variables by using "local" keyword.
local VB="hello world"
echo $VB

Basic conditions
If then else
if [expretion];
then
code for if the expretion is true
else
code for if the expretion is falls
fi
{note the fi in the last line}

eg:-
A="foo"
B="bar"
if ["$A"="$B"]; then
echo "Both are same"
else
echo "Not equal"
fi

For loop

num=10
for i in `seq 1 $num`; do
code
done

While loop
COUNT="0"
while [ $COUNT -lt 10]; do
code
let COUNT=COUNT+1
done

Until loop
COUNT="0"
until [ $COUNT -lt 10 ]; do
code
let COUNT=$COUNT+1
done

No comments:

Post a Comment

Your comments are always welcome ...