Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

用shell腳本實現USB設備掛載與檔案複製

在 Linux 中,插入 USB 設備後需用 mount 掛載命令才能加載。下面是一個 USB 掛載與檔案複製的 Shell 程式,需求如下:

1、運行時提示使用者輸入「y」或「Y」,確認是否掛載 USB 設備(U 盤為 /dev/sdc1)

  1. if [ $ANS = "Y" -o $ANS = "y" ]
  2. then mount -t vfat /dev/sdc1 /mnt/usb

2、確認是否複製檔案到 /root,最好用 $? 判斷是否成功($? -eq 0 表示成功)

  1. while [ $ANS = "Y" -o $ANS = "y" ]
  2. do
  3. ls -lha /mnt/usb
  4. echo "type the filename you want to copy"
  5. read FILE
  6. cp /mnt/usb/"$FILE" /root

3、確認是否複製檔案到 USB 設備中

  1. echo "Do you want to copy files to USB(y/n)"
  2. read ANS
  3. while [ $ANS = "Y" -o $ANS = "y" ]
  4. do
  5. ls -lh /root
  6. echo "type the filename you want to copy"
  7. read FILE
  8. cp /root/"$FILE" /mnt/usb
  9. if [ $? -eq 0 ];then
  10. echo "Finished"
  11. else
  12. echo "Error"
  13. fi
  14. echo "any other files(Y/N)"
  15. read ANS
  16. done

完整腳本:

  1. #!/bin/bash
  2. #autousb
  3. echo "Welcome to USB"
  4. echo "Do you want load USB(Y/N)"
  5. read ANS
  6. if [ $ANS = "Y" -o $ANS = "y" ];
  7. then mount -t vfat /dev/sdc1 /mnt/usb
  8. echo "Do you want to copy files to /root(y/n)?"
  9. read ANS
  10. while [ $ANS = "Y" -o $ANS = "y" ]
  11. do
  12. ls -lha /mnt/usb
  13. echo "type the filename you want to copy"
  14. read FILE
  15. cp /mnt/usb/"$FILE" /root
  16. if [ $? -eq 0 ];then
  17. echo "Finished"
  18. else
  19. echo "Error"
  20. fi
  21. echo "any other files(Y/N)"
  22. read ANS
  23. done
  24. fi
  25. echo "Do you want to copy files to USB(y/n)"
  26. read ANS
  27. while [ $ANS = "Y" -o $ANS = "y" ]
  28. do
  29. ls -lh /root
  30. echo "type the filename you want to copy"
  31. read FILE
  32. cp /root/"$FILE" /mnt/usb
  33. if [ $? -eq 0 ];then
  34. echo "Finished"
  35. else
  36. echo "Error"
  37. fi
  38. echo "any other files(Y/N)"
  39. read ANS
  40. done
  41. echo "Do you want to umount?(y/n)"
  42. read ANS
  43. if [ $ANS = "Y" -o $ANS = "y" ];then
  44. umount /mnt/usb
  45. else
  46. echo "umount error"
  47. fi
  48. echo "GoodBye!!"
Copyright © Linux教程網 All Rights Reserved