Linux shell 脚本实现u盘挂载及文件拷贝
对于linux系统来说。使用mount
命令(需管理员模式使用)来进行挂载硬盘
对于我的虚拟机来说。在插入u盘时,使用sudo fdisk -l
命令设备显示在/dev/sdb1
若硬盘分区不在该目录,需自行修改。
对于取消挂载使用umount
命令
拷贝操作使用cp
命令
第一个参数为出发点,第二个参数为目的地
使用循环菜单来进行功能选择
case
类似与c中case
,1)
表示var
为1时进入。
完整代码如下:
#! /bin/bash
#huangrui 2022/9/20
flag=0
function menu(){
echo "1. mount u "
echo "2. umount u"
echo "3. read u"
echo "4. copy file to u"
echo "5. copy file to system"
echo "enter 6 to exit"
}
function mountU(){
if [ $flag -eq 0 ];then
if [ ! -d "/mnt/usb" ];then
sudo mkdir /mnt/usb
fi
sudo mount /dev/sdb1 /mnt/usb
flag=1
else
echo -e " you have mounted \n"
fi
}
function umountU(){
sudo umount /mnt/usb
}
function readU(){
cd /mnt/usb
ls
cd ..
}
function copyFileToU(){
echo 'please choose your file which you want copy to U'
read path
echo 'please choose the copy destination'
read destination
cp $path /mnt/usb/${destination}S
}
function copyFileToSystem(){
echo 'please choose your file which you want copy to system:'
read path
echo 'plase choose the copy destination:'
read destination
cp /mnt/usb/${path} $destination
}
function main(){
while true
do
menu
read var
case ${var} in
1)
mountU
;;
2)
umountU
;;
3)
readU
;;
4)
copyFileToU
;;
5)
copyFileToSystem
;;
*)
umountU
exit 0
;;
esac
done
}
main
2022/10/05修改,修复了无法从系统复制文件到u盘中的不存在文件夹
#! /bin/bash
#huangrui 2022/9/20
flag=0
function menu(){
echo "1. mount u "
echo "2. umount u"
echo "3. read u"
echo "4. copy file to u"
echo "5. copy file to system"
echo "enter 6 to exit"
}
function mountU(){
if [ $flag -eq 0 ];then
if [ ! -d "/mnt/usb" ];then
sudo mkdir /mnt/usb
fi
sudo mount /dev/sdb1 /mnt/usb
flag=1
else
echo -e " you have mounted \n"
fi
}
function umountU(){
sudo umount /mnt/usb
}
function readU(){
cd /mnt/usb
ls
cd ..
}
function copyFileToU(){
echo 'please choose your file which you want copy to U'
read path
echo 'please choose the copy destination'
read destination
if [ ! -d "/mnt/usb/${destination}" ];then
sudo mkdir /mnt/usb/${destination}
fi
cp $path /mnt/usb/${destination}
}
function copyFileToSystem(){
echo 'please choose your file which you want copy to system:'
read path
echo 'plase choose the copy destination:'
read destination
cp /mnt/usb/${path} $destination
}
function main(){
while true
do
menu
read var
case ${var} in
1)
mountU
;;
2)
umountU
;;
3)
readU
;;
4)
copyFileToU
;;
5)
copyFileToSystem
;;
*)
umountU
exit 0
;;
esac
done
}
main
注意,在使用时需要对脚本进行chmod +x
命令使脚本可以运行
并且,此脚本为bash
脚本,若使用zsh
需自行修改
使用vmware若u盘无法加载,可以在主页面进行usb控制器修改为usb3.1。