Saturday, June 21, 2008

Bash variables scope

Bash variables are defaults to global

What makes a variable local?

  • A variable declared as local is one that is visible only within the block of code in which it appears. It has local "scope." In a function, a local variable has meaning only within that function block.
    Ex:
    local variable name

func ()
{
local loc_var=23
# Declared as local variable.
# Uses the 'local' builtin.
echo "\"loc_var\" in function = $loc_var"
global_var=999

# Not declared as local.
# Defaults to global.
echo "\"global_var\" in function = $global_var"
}

func
# Now, to see if local variable "loc_var" exists outside function.

echo "\"loc_var\" outside function = $loc_var"

# $loc_var outside function =
# No, $loc_var not visible globally
.

echo "\"global_var\" outside function = $global_var"

# $global_var outside function = 999
# $global_var is visible globally
.
exit 0
  • Before a function is called, all variables declared within the function are invisible outside the body of the function, not just those explicitly declared as local

func ()
{
global_var=37

# Visible only within the function block
# before the function has been called.

} # END OF FUNCTION

echo "global_var = $global_var"
# global_var =
# Function "func" has not yet been called,
# so $global_var is not visible here.

func

echo "global_var = $global_var"
# global_var = 37 Has been set by function call.

  • Using the declare builtin restricts the scope of a variable

foo ()
{
FOO="bar"
}


bar ()
{
foo
echo $FOO
}

bar
# Prints bar

However . . .

foo (){
declare FOO="bar"
}
bar ()
{
foo
echo $FOO
}
bar
# Prints nothing.

Bash variables type

Unlike many other programming languages, Bash does not separate its variables by "type". Essentially, Bash variables are character strings, but, depending on context, Bash permits integer operations and comparisons on variables. The determining factor is whether the value of a variable contains only digits.
Integer or string?
a=2334
# Integer.
let "a += 1"
echo "a = $a "
# a = 2335
# Integer, still.

b=${a/23/BB}
# Substitute "BB" for "23".
# This transforms $b into a string
.
echo "b = $b"
# b = BB35
declare -i b
# Declaring it an integer doesn't help.
echo "b = $b"
# b = BB35

let "b += 1"
# BB35 + 1 =
echo "b = $b"
# b = 1
c=BB34
echo "c = $c"
# c = BB34
d=${c/BB/23}
# Substitute "23" for "BB".
# This makes $d an integer
.
echo "d = $d"
# d = 2334
let "d += 1"
# 2334 + 1 =
echo "d = $d"
# d = 2335
# What about null variables?
e=""
echo "e = $e"
# e =
let "e += 1"
# Arithmetic operations allowed on a null variable?
echo "e = $e"
# e = 1
# Null variable transformed into an integer.

# What about undeclared variables?
echo "f = $f"
# f =
let "f += 1"
# Arithmetic operations allowed?
echo "f = $f"
# f = 1
# Undeclared variable transformed into an integer.

The burden is on the programmer to keep track of what type the script variables are.
Bash will not do it for you.
But “declare” or “typeset “built-ins permit restring the properties of variables.
This is very weak form of the typing available in certain programming languages
.

Ex:1
declare –i number
# The script will treat subsequent occurrences of “number” as an integer
number=3
echo “Number = $number”
# Number = 3
number=three
echo “Number = $number”
#Number = 0
#Tries to evaluate the string “three” as an integer

Friday, June 6, 2008

Backup files to tarred and zip file

#!bin/bash

# backs up all files in current directory modified within last 24 hours
# in a tarred and zipped file
# Replace 1 with how many day's you want to back up files

BACKUPFILE=backup-`date +"%m-%d-%Y"`
# Embeds date in backup filename

archive=${1:-$BACKUPFILE}
#If no filename specified default to backup-MM-DD-YYYY

find . -mtime -1 -type f -print0 xargs -0 tar rvf "$archive.tar"

#check bellow command
# tar cvf - $(find . -mtime -1 -type f -print) > $archive.tar
# It works But will fail to backup file names contain space
# if there is no files containing spaces it is good

# ALSO USE bellow code but it is slow and not portable
# find . -mtime -1 -type f -exec tar rvf "$archive.tar" {} \;
# use rvf option instead of cvf otherwise only one file will be archived

gzip $archive.tar && echo "Directory $pwd backed up in \"$archive.tar.gz\" File"

Wednesday, June 4, 2008

Traversing directory using depth first search

#!/bin/bash
# Traverse a directory using depth first traversal technique
# Usage $0 directorypath
# otherwise it takes current working directory as directory path

depth()
{
#Do a small depth checking how deep into the tree we are
k=0
while [ $k -lt $1 ]
do
echo -n " "
let k++
#or use k=`expr $k + 1`
done
}

traverse()
{
# Traverse a directory

ls "$1"while read i
do
depth $2
if [ -d "$1/$i" ]
then
echo Directory: $1/$i
traverse "$1/$i" `expr $2 + 1`
# Calling this as a subshell means that when the called
# function changes directory, it will not affect our
# current working directory
# If you call this in current shell it gives the error
# bash: traverse: No such file or directory after changing
# the current directory
else

echo File: $1/$i
fi
done
}

# $1 is directory path

if [ -z "$1" ]
then
# Here we are giving '0' is the current depth of direcory
traverse . 0
else
traverse $1 0
fi

Friday, April 25, 2008

Displaying chess board on the screen


Small Chess Board


#!/bin/bash
# SCRIPT : smallchessboard.sh
# PURPOSE : Prints small chess board on the screen.

clear
for (( i=1 ; i<=8 ; i++ ))
do

for (( j=1 ; j<=8 ; j++ ))
do

if [ `expr $(($i+$j)) % 2` -eq 0 ]
then
echo -e -n "\033[47m " # White background
else
echo -e -n "\033[40m " # Black background
fi

done
echo # move to next line

done

echo -e "\033[0m" # Restores color settings.


OUTPUT:


Big Chess Board


#!/bin/bash
# SCRIPT : bigchessboard.sh
# PURPOSE : Prints big chess board on the screen.

clear
a=4

for (( i=1 ; i<=8; i++ ))
do

for (( j=1 ;j<=2; j++ )) # prints same line twice
do
tput cup $a 15 # moves cursor to LINE COLUMN

for (( k=1 ; k<=8; k++ ))
do

c=`expr $((i+k)) % 2`

if [ $c -eq 0 ]
then
echo -e -n "\033[40m " # Black background
else
echo -e -n "\033[47m " # White background
fi

done
let a=a+1

done

done

echo -e "\033[0m" # Restores color settings
read key # Waits for enter


OUTPUT:


Tuesday, April 1, 2008

How can get nth line from a file

  1. time head -5 emp.lst tail -1
    It has taken time for execution is
    real 0m0.004s
    user 0m0.001s
    sys 0m0.001s
    or
  2. awk 'NR==5' emp.lst
    It has taken time for execution is
    real 0m0.003s
    user 0m0.000s
    sys 0m0.002s
    or
  3. sed -n '5p' emp.lst
    It has taken time for execution is
    real 0m0.001s
    user 0m0.000s
    sys 0m0.001s
    or
  4. using some cute trick we can get this with cut command
    cut -d “
    “ -f 5 emp.lst
    # after -d press enter ,it means delimiter is newline
    It has taken time for execution is
    real 0m0.001s
    user 0m0.000s
    sys 0m0.001s

    Analysis: comparing above commands 'head' command taken maximum time
    because it pipes the output to tail command. piping consumes some
    time.
    Next “awk” command has taken greater time ,because 'awk' not only
    a command, it is a programing language too.

When not to use shell scripts

· Resource-intensive tasks, especially where speed is a factor (sorting, hashing,
etc.)Procedures involving heavy-duty math operations, especially floating
point arithmetic, arbitraryprecision calculations, or complex numbers
(use C++ or FORTRAN instead)

· Cross-platform portability required (use C or Java instead) Complex applications, where structured programming is a necessity (need type-checking of variables, function prototypes, etc.)

· Project consists of subcomponents with interlocking dependencies Extensive file operations required (Bash is limited to serial file access, and that only in a particularly clumsy and inefficient line-by-line fashion)

· Need native support for multi-dimensional arrays
· Need data structures, such as linked lists or trees
· Need to generate or manipulate graphics or GUIs
· Need direct access to system hardware
· Need port or socket I/O
· Need to use libraries or interface with legacy code

Monday, March 31, 2008

Why shell(bash) programming

No programming language is perfect. There is not even a single best language; there areOnly languages well suited or perhaps poorly suited for particular purposes.
--
UNIX is simple. But It just needs a genius to understand its simplicity.
--Dennis Ritchie
We will be using Bash, an acronym for "Bourne--Again shell" developed by Brian Fox and Chet Ramey. Bash has become a de facto standard for shell scripting on all flavors of UNIX. Bash is the standard GNU shell, intuitive and flexible. Probably most advisable for beginning users while being at the same time a powerful tool for the advanced and professional user. On Linux, bash is the standard shell for common users. This shell is a so-called superset of the Bourne shell, a set of add-ons and plug-ins. This means that the Bourne Again shell is compatible with the Bourne shell. commands that work in sh, also work in bash. However, the reverse is not always the case. Bash is the POSIX compliant.

Shell is a command language interpreter that executes commands read from the standardInput device(key board) or from a file. Shell is not part of system kernel, but uses the system kernel to execute programs, create files etc. Normally shells are interactive. An interactive shell generally reads from, and writes to, a user's terminal: input and output are connected to a terminal.

The UNIX shell program interprets user commands, which are either directly entered by the user, or which can be read from a file called the shell script or shell program. Shell scripts are interpreted, not compiled.Writing shell script is not hard to learn. The syntax is simple and straightforward, similar to that of invoking and chaining together utilities at the command line, and there are only a few rules to learn. Most short scripts work right the first time, and debugging even the longer ones is straightforward. Shell script is just like batch file in MS-DOS but have more power than the MS-DOS batch file. Shell scripts useful to create our own commands that can save our lots of time and to automate some task of day today life. Using shell scripts we can automate system administrative tasks it saves lot of time