LoginSignup
0
3

More than 3 years have passed since last update.

Ubuntuで外付けHDDを自動マウントする

Last updated at Posted at 2020-04-26

fstabを用いた内臓HDDのマウントについては、「Ubuntu 起動時にディスクをマウントする」および、コメント欄を参照ください。

結果的にはfstabを用いれば課題は解決できたのですが、筆者の試行錯誤の記録としてfstabを使わない方法も以下に残しておきます。

課題

NASサーバーであるLinux PCの起動時(ログインする前)に、外付けHDDをマウントしたい。

注意点
外付けHDDがUSBに刺さっていなかったら、マウントせずに起動したい。
したがって、fstabを使えない。
(fstabに記述されたHDDがマウントできないとPCは起動できない)
↑コメント欄を参照のこと!

マウントを実行するシェルスクリプト

外付けHDDが接続されていたらマウントするシェルスクリプト

mountHdd.sh
 #!/bin/bash
 VERBOSE=false 
 if [ "$VERBOSE" == true ]; then
         set -x
 fi

 # Get Device File of HDD
 DEVICE_FILE=$(blkid --uuid 2FCACECF7887A2E1) 
 if [ -z "$DEVICE_FILE" ]; then
         exit 1
 fi

    # Prepare Mount Point 
 MOUNT_POINT="/path/to/mount/point" 
 if [ ! -d $MOUNT_POINT ]; then
         mkdir $MOUNT_POINT
 fi
 # Mount HDD
 mount $DEVICE_FILE $MOUNT_POINT

起動時に実行されるコマンドrc.localに追記

rc.local
 #!/bin/sh
 # output log into /tmp
 exec 1>/tmp/rc.local.log 2>&1  # send stdout and stderr from rc.local to a log file
 set -x                         # tell sh to display commands before execution 

 RET=0

 # mount HDD if connected
 /home/koyama/bin/mountHdd.sh
 RET=$RET && $?

 exit $RET

実行したいシェルスクリプトを作成する(実行権限に注意)

 # 実行可能なrc.localを作成
 sudo vi /etc/rc.local
 sudo chmod u+x /etc/rc.local

 # systemdがrc.localを実行するための設定をする
 cd /etc/systemd/system
 sudo cp /lib/systemd/system/rc-local.service .
 sudo ln -s ../rc-local.service

検証

 sudo systemctl enable rc-local # 起動時に実行されるようにする
 sudo systemctl start rc-local # マウントを実行
 sudo systemctl restart rc-local # マウントを再実行
 sudo systemctl stop rc-local # アンマウントされる(なぜ??)
0
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3