我的挂载脚本不起作用,为什么?

我的挂载脚本不起作用,为什么?
#!/bin/bash
mount | grep 'sda[1-5]'
if [ $? = 0 ]
then
  echo -e "its already mounted ! type u to unmount :\c"
  read word
  if [ $word = "u" || $word = "U" ]
   then 
     umount  /home/shady/Desktop/mountpoint1
     umount  /home/shady/Desktop/mountpoint2
      fi
 fi
if [ $? = 1 ]
then 
  mount /dev/sda1 /home/shady/Desktop/mountpoint1
  mount /dev/sda5 /home/shady/Desktop/mountpoint2
  echo -e "all mounted !!"
fi

它甚至没有进入第一个 if 语句

答案1

这行是你的主要问题:

if [ $word = "u" || $word = "U" ]

我修正了条件,并整理了下面的控制结构:

#!/bin/bash
mount | grep 'sda[1-5]'
if [ $? -eq 0 ]
then
  echo "Volumes are already mounted."
  read -p  "Please type 'u' to unmount:" word
  if [ "$word" = "u" ] || [ "$word" = "U" ]
  then
     echo 'User wishes unmount.  Attempt umount here.'
  fi
else
  echo 'Volumes unmounted.  Attempt mount here.'
fi

看到这个bash 运算符页面举些例子。

答案2

有几个问题。一个[ $? = 0 ]应该是[ $? -eq 0 ]因为$?返回数字,但=对于字符串(文本)是比较。其次,使用[ $word = "u" ] || [ $word = "U" ]或使用[ $word = "u" -o $word = "U" ]。阅读有关这些选项的更多信息man test

不过,我建议使用更简单的解决方案:使用udisksctlutility 而不是media。它更简单,并且可以自动为您完成很多工作。事实上,这是 Ubuntu 默认文件管理器 Nautilus 的后端。

例如,如果我想安装/dev/sda5

  $ udisksctl mount -b /dev/sdb5                                                 
Mounted /dev/sdb5 at /media/xieerqi/0ca7543a-5463-4a07-8bbe-233a7b0bd625

获取卷安装位置的信息:

$ udisksctl info -b /dev/sdb5 | awk '/MountPoints/' 
MountPoints:        /media/xieerqi/0ca7543a-5463-4a07-8bbe-233a7b0bd625

下面是卸载

    $ udisksctl unmount -b /dev/sdb5                                               
Unmounted /dev/sdb5.

相关内容