Thursday, December 23, 2010

Linux-Shell Programming

1. Write a program to print details of currently logged in users,
print date and calendar?
          echo "Current login users: "
          echo "Date: `date`"
          echo "Calendar: `cal`"

2. Write a program to define user defined variables 'x' with value
'10' and 'y' '20' and print it on screen?
          echo "a = $a , b = $b"

3. Write a program to print current shell, present working directory,
and username, using system variable?
          echo "Shell: $SHELL"
          echo "Current Directory: `pwd`"
          echo "User name: `whoami`"

4. Write a program to print the sum of two numbers a=10, b=20?
          echo "Sum: `expr $a + $b`"

5. Write a program to read two numbers from the keyboard and to print
the sum, product and quotient of the numbers?
          echo "Enter the first number: "
          read a
          echo "Enter the second number: "
          read b
          sum=`expr $a + $b`
          echo "Sum is: $sum"
          pro=`expr $a \* $b`
          echo "Product is: $pro"
          quo=`expr $a / $b`
          echo "Quotient is: $quo"

6. Write a program to obtain and print the status of any one command?
          echo "hi"
          if [ $a -eq 0 ]
          echo "Execution successfully completed"
          echo "Execution failed"

7. Write a program to check the following condition:
Read a number from the keyboard; if that number is greater than '0'
then print as "Positive", else print as "Negative”?
          echo "Enter a number: "
          read a
          if [ $a -gt 0 ]
          echo "Number is positive"
          echo "Number is negative"

8. Write a program to implement choices:
                         1. Windows
                         2. Linux
                         Select your choice [1 or 2]
Read the choice from keyboard. If that is '1' the print "Windows", if
that is '2' then print "Linux" else print "You don’t like Windows or
          echo "1. Windows"
          echo "2. Linux"
          echo "    Select [1 or 2]"
          read ch
          if [ $ch -eq 1 ]
          echo "Windows"
          else if [ $ch -eq 2 ]
          echo "Linux"
          echo "You dont like Windows or Linux"

9. Write a program to prepare students record consisting of name,
roll no, and marks of three subjects. Take sum of the three marks and
print all details of student with total mark?
          echo "Enter Student Details"
          echo "Name: "
          read name
          echo "Roll No: "
          read roll
          echo "Mark1: "
          read m1
          echo "Mark2: "
          read m2
          echo "Mark3: "
          read m3
          tot=`expr $m1 + $m2 + $m3`
          echo "Student Record"
          echo "Name: $name"
          echo "Roll No: $roll"
          echo "Total marks: $tot"

10. Write a program to print cut 5 to 8 columns from any textile?
          cut -c 5-8 textile

11. Write a simple program using awk?
          awk '{ print $1 }' textile

12. Write a program to search a specific word from a file, first read
word from keyboard then using grep command search that word, and take
status of that command, if status is success the print "Word Found"
else print "Word not Found"?
          echo "Enter a pattern to search"
          read pat
          grep $pat textile
          if [ $? -eq 0 ]
          echo "Word Found"
          echo "Not found"

Linux-More commands

To show the full path of shell commands found in your path
     which <command name>
          eg: which grep
               //output like: /bin/grep

To locate the program, source code, and manual page for a command
     whereis <command name>
To search for files anywhere on the file system
     locate <keyword to search>
           //find all files and directories that contain the keyword

To search for files matching certain patterns
     find <directory name> <pattern to search>
           eg: find . -name \*mp3
           //starts searching in the current directory “.” and all
subdirectories, looking for files with “mp3” at the end of their

To list currently running process
To list all process in the system
     ps -aux
To show who is logged on and what they are doing
To view the name of current user
To view the user details
To view host name
To set host name
     hostname -a <new host name>
To print your user-id and group id's
To get report on file system disk space usage
     df -h
To view disk usage in a particular directory
To view summary
     du -s
     du -h
To display CPU processes in a full-screen GUI
     // type “Q” to quit
To display amount of free and used memory in the system
To display information about your CPU
     cat /proc/cpuinfo
To display lots of information about current memory usage
     cat /proc/meminfo
To print system information to the screen
     uname -a
To print kernel version
     uname -r
To display the size of a file
     wc -l
In bytes
     wc -m
In char
     wc -c
In word count
     wc -w
To change permission to a file/directory
     chmod [-R] <permissions> <file name/directory name>
           eg: chmod 754 one.txt
           eg: chmod -R 777 /home/songs/
     read r=4; write w=2; execute x=1
     Owner      Group     Others
     rwx        r-x       r--
     7          5         4
To change ownership of a file/directory
     chown [-R] <user name> <file name/directory name>
           eg: chown dhanoop one.txt
           eg: chown -R dhanoop /home/songs/
To search a file for a particular pattern
     grep [-R] <word to search> <file name/directory name>
           eg: grep science science.txt
                //case-sensitive search
           eg: grep -i science science.txt
                //case-insensitive search
           eg: grep -i ‘spinning top’ science.txt
                //multiword search
           eg: grep -R passwd /etc/
                //search in directory
To clear the screen
To display text on screen
     echo “<text to display>”
           eg: echo “Hello”
To print a file or program output
     lpr <file name>
           eg: lpr mp3files.txt
     <command> | lpr
           eg: ls -la | lpr
To sort a file or program output
           eg: sort mp3files.txt
To switch user
     su <user name>
           //to switch to a particular user account
           //to switch to root account
     su -
           //to switch to root, and log in with root's environment
To give an alias name to a command for ease of use
     alias <name>=”<command>”
           eg: alias list=”ls -l”
To display last logins of user
To display the name of currently working terminal
To block a user
     passwd -l <user name>
To unblock a user
     passwd -u <user name>
To add a user account
     useradd [options] <username>
With specified home directory
     useradd -d <home directory> <user name>
With specified shell
     useradd -s <shell> <user name>
With specified initial group
     useradd -g <initial group> <user name>
With specified expiry date
     useradd -e <YYYY-MM-DD> <user name>
To lock/unlock a user account
     usermod [-L or -U] <user name>
To delete a user account
     userdel [-r] <user name>
To restart the system
     shutdown -r now
          //without delay
To turn off the system
To reboot the system
To halt the system
To mount a file system or media
     mount <source> <destination>
          eg: mount /dev/sda1 /mnt
                //mounting first partition of first SATA hard disk
          eg: mount /dev/hdb3 /mnt
                //mounting third partition of second hard disk
To umount a file system or media
     umount <file system/media>
          eg: umount /mnt
To view IP address
To edit IP address temporarily
     ifconfig -a etho <ipaddress>
To view partitions and file systems
     fdisk -l
          //view line by line
To print selected columns in a file
     cut -c <column range> <file name>
          eg: cut -c 3-5 sem.txt
To print particular fields
     awk ‘{ print $<field number> }’ <file name>
          eg: awk ‘{ print $2 }’ sem.txt
                //prints second field
          eg: awk ‘{ print $1 $3 }’ sem.txt
                //prints first and third fields
To know the shell
     echo $SHELL
          //the symbol “$” precedes every user or system variable.
          All system variables are BLOCK lettered.
To know the home directory
     echo $HOME
To print the calendar
          //prints calendar of current month
     cal <YYYY>
          eg: cal 2010
                //prints calendar of specified year
To print the date
To temporarily switch to root to execute a single command
     sudo <command>
          eg: sudo ifconfig -a eth0
To run an executable file
     sh <file name>
          eg: sh new\ file
                //”\ “ denotes white space
     ./<file name>
          eg: ./new\ file
To view command history
To re execute last command
To execute nth command in history
          eg: !444
                //executes 44th command in the history
To re execute last command that starts with specified character
          eg: !s
              //executes the last command that starts with letter “s”
To repeat the last command changing old character to new character
          eg: ^l^m
                //let “wc -l” be the last command
                     now “wc -m” will be executed

Signals to a process
To list all signals
     kill -l
To kill a process
     kill <process id>                                   
To terminate a process
     kill -9 <process id>
To normally exit a process
     kill -15 <process id>

To login remotely to a system
     ssh [<user name>@]<ip address>
          eg: ssh dhanoopbhaskar@
To execute a command on remote system through remote login
     ssh [<user name>@]<ip address> <command>
          eg: ssh dhanoopbhaskar@ df -h
               //executing “df -h” remotely
To copy file from a remote system
     scp [-r] <source> <destination>
          eg: scp /home/a.c dhanoopbhaskar@

Linux-Working with files

To find the type of a file
     file <file name>
To create a file
     cat > filename.txt
          //type the contents and press Ctrl+D to exit
To display the contents of a text file
     cat <file name>
To view the contents of a file page by page
     more <file name>
          //traversal only in forward direction
     less <file name>
          //traversal in both directions
To display first few lines of a file
     head <file name>
     head -5 <file name>
          //first 5 lines
To display last few lines of a file
     tail <file name>
     tail -5 <file name>
          //last 5 lines
To display the last few lines of a text file, and then output
appended data as the file grows (very useful for following log
     tail -f /var/log/messages
To copy a file from one location to another
     cp [-r] <source file/directory> <destination>
          eg: cp mp3files.txt /tmp
To move a file to a new location
     mv <source> <destination>
          eg: mv mp3files.txt /tmp
To delete a file
     rm [-r] <filename/directory name>
          eg: rm /tmp/mp3files.txt

Linux-Working with directories

To print working directory

To change directory
To return to home directory
To change into specified directory name
     cd <directory name>
To change to home or other path relative to home.
“~” is an alias for your home directory
     cd ~
To move up one directory
     cd ..
To return to previous directory
     cd -

To list all files in the current directory
To list all files in the current directory, in column format
To list the files in the specified directory
     ls <directory name>
To list files in “long” format, 1 file per line with additional
     ls -l
To list all files, including “hidden” files
     ls -a
To show the directory's detailed information
     ls -ld <directory name>
To list all files whose names begin with the letter “d” in the
/usr/bin directory
     ls /usr/bin/d*
To list files based on their size
     ls -sh

To create a directory
     mkdir <directory name>
          eg: mkdir dhan
     mkdir -p <directory path>
          eg: mkdir -p /home/sng/dhan

To create directories in multiple paths
     mkdir -p parent/{child1,child2,child3}
          eg: mkdir -p work/{in,out,pending}/{a,b,c}

To delete a directory
     rmdir <directory name>
          eg: rmdir /tmp/myfiles/

Linux-help commands

To get help on commands
     help <command name>
          eg: help cat
     <command name> --help
          eg: grep --help
     <command name> -h
          eg: chmod -h
     whatis <command name>
          eg: whatis grep

To get “man” pages
     man <command name>
          eg: man ls
To search for a particular word within a man page
     type “/word”.
To quit from a man page, just
     type the “Q” key.
If you don’t remember the actual command
     man -k <keyword to search>
          eg: man -k permission
          You will find a line in the output that looks something
like: chmod (1) - change file access permissions

To get “info” pages
     info <command name>

Linux-Directory Layout


The nameless base of the file system. All other directories, files, drives, and devices are attached to this root. Commonly (but incorrectly) referred to as the “slash” or “/” directory. The “/” is just a directory separator, not a directory itself.
Essential command binaries (programs) are stored here (bash, ls, mount, tar, etc.)
Static files of the boot loader.
Device files. In Linux, hardware devices are accessed just like other files, and they are kept under this directory.
Host-specific system configuration files.
Location of users' personal home directories (e.g./home/dhanoop).
Essential shared libraries and kernel modules.
Process information pseudo-file system. An interface to kernel data structures.
The root (super-user) home directory.
Essential system binaries (fdisk, fsck, init, etc).
Temporary files. All users have permission to place temporary files here.
The base directory for most shareable, read-only data (programs, libraries, documentation, and much more).
Most user programs are kept here (cc, find, du, etc.).
Header files for compiling C programs.
Libraries for most binary programs.
Locally” installed files. This directory only really matters in environments where files are stored on the network. Locally-installed files go in /usr/local/bin, /usr/local/lib, etc.). Also often used for software packages installed from source, or software not officially shipped with the distribution.
Non-vital system binaries (lpd, useradd, etc.)
Architecture-independent data (icons, backgrounds, documentation, terminfo, man pages, etc.).
Program source code. E.g. The Linux Kernel, source RPMs, etc.
The X Window System.
Variable data: mail and printer spools, log files, lock files, etc.


Escape character. If you want to reference a special character, you must “escape” it with a backslash first.
Example: touch /tmp/filename\*
Directory separator, used to separate a string of directory names.
Example: /usr/src/linux
Current directory. Can also “hide” files when it is the first character in a filename.
Parent directory
User's home directory
Represents 0 or more characters in a filename, or by itself, all files in a directory.
Example: pic*2002 can represent the files pic2002, picJanuary2002,picFeb292002, etc.
Represents a single character in a filename.
Example: hello?.txt can represent hello1.txt, helloz.txt, but not hello22.txt
[ ]
Can be used to represent a range of values, e.g. [0-9], [A-Z], etc.
Example: hello[0-2].txt represents the names hello0.txt,hello1.txt, and hello2.txt
Pipe”. Redirect the output of one command into another command.
Example: ls | more
Redirect output of a command into a new file. If the file already exists, over-write it.
Example: ls > myfiles.txt
Redirect the output of a command onto the end of an existing file.
Example: echo .Mary 555-1234. >> phonenumbers.txt
Redirect a file as input to a program.
Example: more < phonenumbers.txt
Command separator. Allows you to execute multiple commands on a single line.
Example: cd /var/log ; less messages
Command separator as above, but only runs the second command if the first one
finished without errors.
Example: cd /var/logs && less messages
Execute a command in the background, and immediately get your shell back.
Example: find / -name core > /tmp/corefiles.txt &


class Threading {
     public static void main(String[] args) {

           /*Method No.1
Counter ctr = new Counter();
           /*Method No.2*/
           Thread thread = new Thread(new Counter());

/*Method No.1
class Counter extends Thread {
     public void run() {
           int ctr = 1;

           while (ctr <= 10) {
                try {
                } catch (InterruptedException ex) {

/*Method No.2*/
class Counter implements Runnable {
     public void run() {
           int ctr = 1;

           while (ctr <= 10) {
                try {
                } catch (InterruptedException ex) {

Java-TCP socket programming


public class Client1 {
  public static void main(String[] args) throws Exception {
    String hostAddr = ""; // Loopback Address
    int hostPort = 8000;

    System.out.println("Client requesting for connection...");
    Socket clientSideSocket = new Socket(hostAddr, hostPort);
    System.out.println("Connection established.");

    PrintWriter serverWriter = new PrintWriter(
                clientSideSocket.getOutputStream(), true);

    System.out.println("Key in a message for the server:");
    serverWriter.println(new BufferedReader(
                new InputStreamReader(;
    System.out.println("Message sent to server.");
---------------------- ----------------------

public class Server1 {
  public static void main(String[] args) throws Exception {
    int port = 8000;
    ServerSocket serverSocket = new ServerSocket(port);

    System.out.println("Server Started. Waiting for connection...");
    Socket serverSideClientSocket = serverSocket.accept();
    System.out.println("Client connection request received.");
    System.out.println("Sockets bound and ready for communication.");

    BufferedReader clientReader = new BufferedReader(new InputStreamReader(
    System.out.println("Waiting for message from client...");
    String messageFromClient = clientReader.readLine();
    System.out.println("Client says: " + messageFromClient);


public class Client2 {
  public static void main(String args[]) {
    try {
      Socket clientSideSocket = new Socket("localhost", 8000);
      BufferedReader serverReader = new BufferedReader(
                new InputStreamReader(clientSideSocket.getInputStream()));
      PrintWriter serverWriter = new PrintWriter(
                     clientSideSocket.getOutputStream(), true);
                BufferedReader keyboardReader = new BufferedReader(
                     new InputStreamReader(;
                double radius = 0;
      while (true) {
        System.out.print("Please enter the Radius of a Circle...");
        radius = Double.parseDouble(keyboardReader.readLine());
                     if (radius != 0) {
                           double area = Double.parseDouble(
                           System.out.println("Area received from the Server: " +
                     } else {
    } catch(IOException e) {

---------------------- ----------------------

public class Server2 {
  public static void main(String[] args) {
    try {
      ServerSocket serverSocket = new ServerSocket(8000);
      Socket serverSideClientSocket = serverSocket.accept();

      BufferedReader clientReader = new BufferedReader(
                     new InputStreamReader(
      PrintWriter clientWriter = new PrintWriter(
                     serverSideClientSocket.getOutputStream(), true);
      while (true) {
        double radius = Double.parseDouble(clientReader.readLine());
                     if (radius != 0) {
                           System.out.println("Radius Received from Client: " +
                           double area = radius * radius * Math.PI;
                     } else {
    } catch(IOException e) {

Wednesday, December 22, 2010

Java-Serialization and De-serialization


public class Student implements Serializable {
private int rollNo;
private String name;
transient int age;
public Student(int rollNo, String name, int age) {
this.rollNo = rollNo; = name;
this.age = age;
public int getRollNo() {
return rollNo;
public String getName() {
return name;

public class TestObjectInputStream {
public static void main(String s[]) throws IOException,
ClassNotFoundException {
/*FileInputStream fileInStream =
new FileInputStream("Student.ser");
ObjectInputStream objInStream =
new ObjectInputStream(fileInStream);*/

ObjectInputStream objInStream =
new ObjectInputStream(
new FileInputStream("Student.ser"));

System.out.println("Deserializing object s1...");
Student s1 = (Student) objInStream.readObject();
System.out.println("Object s1 deserialized.");

System.out.println("Roll No.: " + s1.getRollNo());
System.out.println("Name : " + s1.getName());
System.out.println("Age : " + s1.age);


public class TestObjectOutputStream {
public static void main(String s[]) throws IOException {
/*FileOutputStream fileOutStream =
new FileOutputStream("Student.ser");
ObjectOutputStream objOutStream =
new ObjectOutputStream(fileOutStream);*/

ObjectOutputStream objOutStream =
new ObjectOutputStream(
new FileOutputStream("Student.ser"));

Student s1 = new Student(12, "Arvind", 14);

System.out.println("Serializing object s1...");
System.out.println("Object s1 serialized.");

Java-Renaming a file


class TestFile {
public static void main(String[] args) throws Exception {
File file = new File(args[0]);

File oldFile = new File("a.txt");
File newFile = new File("b.txt");

if (new File("a.txt").renameTo(new File("b.txt"))) {
} else {


Java-Moving a file


public class MoveFile {
public static void main(String args[]) throws IOException {
switch (args.length) {
case 0:
System.out.println("Error in usage:");
System.out.println("Usage: java MoveFile ");
case 1:
System.out.println("Specify the destination file.\n");
System.out.println("\tUsage: java MoveFile ");
case 2:
File source_file = new File(args[0]);
File dest_file = new File(args[1]);

* If the file does not exist, show an error message *
* and stop the program. *
if (! source_file.exists()) {
System.out.println(args[0] + " Not Found !!!");

* If the file exists, ask if the file is to be overwritten. *
* (i) If the response is "Y" or "y", then overwrite it by *
* invoking the move method. *
* (ii)If the response is "N" or "n", then cancel move operation. *
if (dest_file.exists()) {
System.out.print(args[1] + " file already exists. Overwrite? (y/n): ");
int response =;
if (response == 'Y' || response == 'y') { // if you do not want to overwrite the file.
moveFile(source_file, dest_file); // user-defined function
} else {
System.out.println("File move operation aborted !!!");
} else {
moveFile(source_file, dest_file);
public static void moveFile(File source_file, File dest_file) throws IOException {
System.out.print("Move file? (y/n): ");;//Emptying the Keyboard Buffer.
int response =;
if (response == 'Y' || response == 'y') { // if you want to move the file.
* Creating streams for reading and writing source/destination files. *
String source_file_str = source_file.getAbsolutePath();
String dest_file_str = dest_file.getAbsolutePath();

String source_file_dir =
source_file_str.lastIndexOf('\\'));//truncating the filename
String dest_file_dir =

System.out.println("Source File Abs Path: " +
System.out.println("Source Dir: " + source_file_dir);
System.out.println("Dest File Abs Path: " + dest_file_str);
System.out.println("Dest Dir: " + dest_file_dir);

if (source_file_dir.equals(dest_file_dir)) {
System.out.println("Renaming file " +
source_file.getName() + " to " +
dest_file.getName() + " !!!");
source_file.renameTo(new File(dest_file.getName()));
} else {
FileInputStream input_file = new FileInputStream(
FileOutputStream output_file = new FileOutputStream(
* (i) Finding the size of the source file using available(). *
* (ii) Creating a byte array, the no. of elements of which is equal *
* to the size of source file. *
* (iii)Read data from the source file into the byte array. *
* (iv) Write the byte array to the destination file. *
System.out.println("Moving file " +
source_file.getName() + " to " +
dest_file.getName() + " !!!");
int file_size = input_file.available();
byte input_file_data[] = new byte[file_size];;

* Close the input/output streams. *


* Delete the source file and return a successful process message. *

System.out.println("File " + source_file.getName() +
" successfully moved to " + dest_file.getName() + " !!!");
} else {// if you do not want to move the file.
System.out.println("File move operation aborted !!!");

Java-Copying a file


public class CopyFile {
public static void main(String[] args) throws IOException {
switch (args.length) {
case 0:
System.out.println("Error in usage:");
" Usage: java CopyFile ");
case 1:
"Specify the destination file.");
" Usage: java CopyFile ");
case 2:
File sourceFile = new File(args[0]);
File destFile = new File(args[1]);

if (! sourceFile.exists()) {
System.out.println(args[0] + " not found !!!");
System.exit(0); // stopping application

if (destFile.exists()) {
System.out.print(args[1] +
" file already exists. Overwrite? (y/n): ");
int response =;
if (response == 'N' || response == 'n') {
// if you do not want to overwrite the file.
System.out.print("Copy operation aborted.");
System.exit(0); // stopping application

System.out.println("Copying file...\n" +
args[0] + " to " + args[1]);

FileInputStream inputFile =
new FileInputStream(sourceFile);
FileOutputStream outputFile =
new FileOutputStream(destFile);

//boolean arg is for "append"
/*FileOutputStream outputFile =
new FileOutputStream(destFile, true);

FileOutputStream outputFile =
new FileOutputStream(args[1]);

FileOutputStream outputFile =
new FileOutputStream(args[1], true);*/

byte[] inputFileData =
new byte[inputFile.available()];;


System.out.println("File successfully copied !");


/*File oldFile = new File("abc.txt");
File newFile = new File("xyz.txt");

new File("abc.txt").renameTo(new File("xyz.txt"));*/

Java-Writing to a file


public class WriteFile {
public static void main(String args[]) throws IOException {
if (args.length != 0) {
File file = new File(args[0]);

if (file.exists()) {
System.out.print("This file already exists. Overwrite? (y/n): ");
int response =;
if(response == 'N'||response =='n') {
// if you do not want to overwrite the file.
System.exit(0); // stop program
} else {
System.out.print("Creating new file: " + args[0] + "...");

"[Press \'~\' as the first char on a new line to terminate the file.]");
System.out.println("Enter data for file: " + args[0]);

FileOutputStream output_file = new FileOutputStream(file); // output file.
boolean continue_write = true;
byte[] data; // byte array to which the data is read into.
while (continue_write) {
// continue reading lines till the user types '~' and ENTER.
data = new BufferedReader(
new InputStreamReader(;
if (data.length == 1 && ((char)data[0]) == '~') {// if end-of-file
continue_write = false;
} else {// if not end-of-file
} else {//end of while
System.out.println("Usage: java WriteFile ");

/*public class WriteFile
public static void main(String args[]) throws IOException
File file=new File(args[0]);

System.out.print("This file already exists. Overwrite? (y/n): ");
// if you do not want to overwrite the file.
System.exit(0); // stop program
System.out.print("Creating new file: " + args[0] + "...");

"[Press \'~\' as the first char on a new line to terminate the file.]");
System.out.println("Enter data for file: " + args[0]);

PrintWriter output_file=new PrintWriter(
new FileOutputStream(file), true); // output file.
boolean continue_write=true;
String line;
// continue reading lines till the user types '~' and ENTER.
line=new BufferedReader(new InputStreamReader(;
if(line.length()==1 && line.equals("~")) // if end-of-file
else // if not end-of-file
System.out.println(“Usage: java WriteFile ”);

Java-Reading a file


public class ShowFile {
  public static void main(String args[]) throws IOException {
    if (args.length != 0) {
      File file = new File(args[0]);
      if (file.exists() && file.isFile()) {
        FileInputStream input_file =
                           new FileInputStream(file);
        /*FileInputStream input_file =
                     new FileInputStream(args[0]);*/
        int file_size = input_file.available();
        byte[] data = new byte[file_size];;
        System.out.println(new String(data));
      } else {
        System.out.println("\"" + args[0] +
                           "\" not found !!!");
    } else {
      System.out.println("Error in usage:");
                     "  Usage - java ShowFile ");

Contact Form


Email *

Message *