红联Linux门户
Linux帮助

Ubuntu检测磁盘是否挂载

发布时间:2016-07-03 10:11:50来源:linux网站作者:mitoxR
Ubuntu默认不自动挂载磁盘。
只是学习Bash使用,需优化如使用。
 
# file: mountAll.sh
# include color support
# a list of variables containing color code in xterm256
. bash.colors
# check if 
function isMounted {
disk=$1
for d in `mount -l | awk '{print $1}' | sort |uniq`;do
if test "x$disk" = "x$d" ;then
# use `=' for string comparison, and `-eq' for numbers in SHELL
# in Perl5, string comparison is `eq' while numeric comparison is `='
# I prefer the Perl way
echo 1
# mounted
return
fi
# Note
# the `commands` capture data from stand out or function return value
done
echo 0
# not mounted
return
}
function isAllMounted(){
# check if there is disk not mounted
for disk in '/dev/sdb1' '/dev/sdc1' '/dev/sdc2';do
if test `isMounted $disk` -eq 0;then
# 0 not mounted, 1 mounted
echo 0
return
fi
done
echo 1
# 1 all mounted, 0 at least 1 disk not mounted
return
}
mount3IfThereIsNotMounted(){
if [ `isMounted '/dev/sdb1'` -eq 0 ];then
sudo /bin/mount /dev/sdb1 /mnt/data1 2>/dev/null
fi
if [ `isMounted '/dev/sdc1'` -eq 0 ];then
sudo /bin/mount /dev/sdc1 /mnt/data2 2>/dev/null
fi
if [ `isMounted '/dev/sdc2'` -eq 0 ];then
sudo /bin/mount /dev/sdc2 /mnt/data3 2>/dev/null
fi
}
if [ -x /usr/bin/sudo ];then
# check that the sudo is visible to the current login user
case " $(groups) " in
# if $USER is in the adm group
*\ adm\ *)
if [ `isAllMounted` -eq 0 ];then
# at least one disk not mounted
mount3IfThereIsNotMounted
if [ `isAllMounted` -eq 1 ];then
echo -e "${green}adm:Disks prepared\033[00m"
else
echo -e "${red}adm:Not all disks prepared\033[00m"
fi
else
echo -e "${blue}adm:Disks prepared\033[00m"
fi;;
*\ sudo\ *)
# if $USER is in the adm group
if [ !`isAllMounted` ];then
mount3IfThereIsNotMounted
if [ `isAllMounted` -eq 1 ];then
echo -e "${green}sudo:Disks prepared$endc"
else
echo -e "${red}sudo:Not all disks prepared$endc"
fi
else
echo -e "${blue}sudo:Disks prepared$endc"
fi;;
*)
if [ `isAllMounted` -eq 1 ];then
echo -e "${blue}Disks prepared$endc"
else
echo -e "${red}Not all disks prepared$endc"
fi;;
esac
fi
 
如果没挂载要输入密码,可以把密码embeded到expect脚本中。
# file mountSilent
#!/usr/bin/expect
spawn bash mountAll.sh
expect "password\r"
send "********"
interact
 
Color 8
#file: bash.colors
prefix='\033[01;'
endc='\033[00m'
black=$prefix"30m"
red=$prefix"31m"
green=$prefix"32m"
yellow=$prefix"33m"
blue=$prefix"34m"
fuchsia=$prefix"35m"
ultramarine=$prefix"36m"
white=$prefix"37m"
bg_black=$prefix"40m"
bg_red=$prefix"41m"
bg_green=$prefix"42m"
bg_yellow=$prefix"44m"
bg_blue=$prefix"44m"
bg_fuchsia=$prefix"45m"
bg_ultramarine=$prefix"46m"
bg_white=$prefix"47m"
 
本文永久更新地址:http://www.linuxdiyf.com/linux/22018.html