Tuesday, February 22, 2011

How to write shell script

1. Type following cat command:
$ cat > first
#
# My first shell script
#
clear
echo "Knowledge is Power"
echo -e "An apple a day keeps away \a\t\tdoctor\n"
$ echo "Today is date"
$ echo "Today is `date`"
Press Ctrl + D to save. Now our script is ready.
2. Set Execute permission for our script first:
$ chmod +x first
3. Run the shell script
$ ./first
Or: $ bash first
Or: $ /bin/sh first

Addition:
1. Type bc at $ prompt to start Linux calculator program, quit to exit
$ bc
After this command bc is started and waiting for you commands, i.e. give it some calculation as
follows type 5 + 2 as
5 + 2
7
Now what happened if you type 5 > 2 as follows
5 < 2
0
0 (Zero) is response of bc, false
2. eg.
$ cat > demo
#!/bin/sh
#
# Script that demos, command line args
#
echo "Total number of command line argument are $#"
echo "$0 is script name"
echo "$1 is first argument"
echo "$2 is second argument"
echo "All of them are :- $*"
executable & run:
$ chmod +x demo
$ ./demo Hello World
3. eg. show file
$ cat > showfile
#!/bin/sh
#
#Script to print file
#
if cat $1
then
echo -e "\n\nFile $1, found and successfully echoed"
fi
Now run it.
$ chmod +x showfile
$./showfile foo
4. eg. delete file
#
# Script to test rm command and exist status
#
if rm $1
then
echo "$1 file deleted"
fi
(Press Ctrl + d to save)
$ chmod +x trmif
$ ./trmfi foo
5. eg. for loop
$ cat > testfor
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done
Run it as,
$ chmod +x testfor
$ ./testfor
6. eg.
n=$1
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "$n * $i = `expr $i \* $n`"
done
Save and Run it as
$ chmod +x mtable
$ ./mtable 7
7. eg. the read statement
$ cat > sayH
#
#Script to read your name from key-board
#
echo "Your first name please:"
read fname
echo "Hello $fname, Lets be friend!"
Run it as follows
$ chmod +x sayH
$ ./sayH
8. eg.
To run two command with one command line.For eg. $ date;who ,Will print today's date followed by users who are currently login.
9. eg. function
$ SayHello()
{
echo "Hello $LOGNAME, Have nice computing"
return
}
Now to execute this SayHello() function just type it name as follows
$ SayHello