Wednesday, May 12, 2010

Script to mount partitions from image file in linux

#!/bin/bash

usage ()
{
    cat <<EOF
Usage: $(basename $0) <image file>
EOF
exit 1;
}

# Check for the input argument
if [ $# -ne 1 ]; then
    usage
fi

sfdisk -l -uS $1 

sfdisk -l -uS $1 2>/dev/null | awk '
           BEGIN {
             i = 1
           }
           /sectors\/track$/ {
             split ($2, array, ":"); 
             imagefile = array[1];
           }
           /^Units = sectors of/ {
             secsize = $5;
           }
           !/#sectors|sectors\/track$|^$|^Units = sectors of/ && $4 != 0 {
             partoffset = secsize * $2;
             cmd = sprintf ("test -e /mnt/tttt%d", i);
             cmd1 = sprintf ("test -d /mnt/tttt%d", i);
             if (system (cmd) != 0)
             {
               cmd = sprintf ("mkdir /mnt/tttt%d 2>/dev/null", i);
               if (system (cmd) != 0)
               {
                 printf ("Error: Could not create the director /mnt/tttt%d.Please try with root privilege.\n", i);
                 exit;
               }
             }
             else if (system (cmd) != 0)
             {
               printf ("Error: /mnt/tttt%d is not a directory.\n", i);
               exit;
             }
             cmd = sprintf ("mount -o loop,offset=%d %s /mnt/tttt%d", partoffset, imagefile, i); 
             if (system (cmd) != 0)
             {
               exit;
             }
             printf ("Mounting: %s ---> /mnt/tttt%d\n", $1, i);
             i++;
           }'

  To run this script:
  root@ubuntu:~# mountImageFile.sh <image file>

  Run this script with root privilege.

Note: This script will not work for large partitions because of the limitation in sfdisk.
Reference: http://lists.samba.org/archive/linux/2005-April/013444.html & manpages awk and sfdisk

No comments :

Post a Comment