在学习bochs模拟器的使用过程中,为了能直接和其磁盘映像文件交换文件,其中一种方法是先用 losetup 命令将映像联结到回环设备,再用 mount 命令挂载, 卸载时再用相反的步骤(见: bochs的使用)。为了让操作更简便,我自己写了一个Shell脚本,这是我写的第一个Shell脚本,让我体会到了Linux过滤器的组合乐趣,我把代码贴出来,和大家分享,也请大虾们指点指点。
#!/bin/bash
#
#set up and mount image file with loop devices
#Author: Hawkxp
#Date : 2006/8/27
#
ERR_USAGE="The usage is wrong! Please try "--help" option."
if [ $# -gt 3 ]
then
echo -e "$ERR_USAGE"
exit 1
fi
opt=''
opt_img=''
opt_dir=''
for arg in "$@"
do
if [ "${arg:0:1}" = "-" ]
then
opt=$arg
elif [ -f $arg -a -z "$opt_img" ]
then
opt_img=$arg
elif [ -d $arg -a -z "$opt_dir" ]
then
opt_dir=$arg
fi
done
if [ -z "$opt" -a -n "$opt_img" -a -n "$opt_dir" ]
then
if [ `ls -l $opt_img | awk '{print $5}'` = "1474560" ]
then
opt='-o512'
else
opt='-o32256'
fi
fi
mntimg_list(){
local lodev=''
for lodev in `mount | grep '/dev/loop' | awk '{print $1}'`
do
echo -en "${lodev} "
echo -en "`mount | grep $lodev | awk '{print $3}'` "
echo "`losetup $lodev | cut -f 2 -d '(' | cut -f 1 -d ')'`"
done
if [ -z "$lodev" ]
then
echo "none is mounted yet."
fi
}
mntimg_mount(){
local newdev=`losetup -f`
if [ "${newdev%?}" != "/dev/loop" ]
then
echo "no more loop device, Please umount one first!"
exit 1
fi
if [ -n `mount | grep "$3"` ]
then
echo "Directory $3 was mounted!"
exit 1
fi
if [ -n "`losetup -o $1 $newdev $2`" ]
then
echo "failed on set up to loop device."
exit 1
fi
if [ -n "`mount -o loop $newdev $3`" ]
then
echo "failed on mount to ${3}."
losetup -d $newdev
exit 1
fi
echo "success mount."
}
mntimg_umount(){
local lodev=''
local no=0
if [ -d $1 ]
then
lodev=`mount | grep "${1%/}" | awk '{print $1}'`
else
until [ $no -eq 8 ]
do
lodev=`losetup /dev/loop$no 2>/dev/null | grep "${1##*/}" | awk '{print $1}'`
if [ -n "$lodev" ]
then
lodev=${lodev%:}
no=8
else
no=$(( $no+1 ))
fi
done
fi
if [ -z "$lodev" ]
then
echo "not mounted yet."
exit 1
fi
umount $lodev
losetup -d $lodev
echo "umount success"
}
case "$opt" in
--help | -h)
echo "usage:"
echo " mountimg {--help | -h} :print this help"
echo " mountimg {--list | -l} :list info of the mounted image"
echo " mountimg [-o{offset}] img dir :mount image to directory"
echo " mountimg {--umount|-u} {img|dir} :umount"
exit 1
;;
--list | -l)
mntimg_list
;;
-o*)
if [ -z "$opt_img" ]
then
echo "Image file is not found."
echo -e $ERR_USAGE
exit 1
fi
if [ -z "$opt_dir" ]
then
echo "Directory is not found."
echo -e $ERR_USAGE
exit 1
fi
mntimg_mount ${opt#-o} $opt_img $opt_dir
;;
--umount | -u)
if [ -z "$opt_img" -a -z "$opt_dir" ]
then
echo "Image or directory is not found."
echo -e $ERR_USAGE
exit 1
elif [ -n "$opt_dir" ]
then
mntimg_umount $opt_dir
else
mntimg_umount $opt_img
fi
;;
*)
echo -e $ERR_USAGE
;;
esac
将脚本文件保存为 ~/bin/mountimg 中,执行命令 “chmod a+x ~/bin/mountimg" 给文件加上执行属性,就可以使用了,输入 ”mountimg --help" 查看使用帮助:
mountimg --list :查看当前已挂载的映像列表
mountimg [-o{offset}] img dir :将映像文件(img)挂载到目录(dir),
-o是可选项,后跟映像分区的起始地址(512B × 扇区数)
注意和“-o”间无空格。默认为第一分区
mountimg --umount {img | dir} :卸载指定的已挂载映像
使用的参考资料:Shell编程系列