LoginSignup
4
5

WSL上のデータをWindows領域に自動的にバックアップする

Last updated at Posted at 2023-12-15

WSL Ubuntuのデータを定期的にWindows領域にバックアップする設定方法について記します。

背景

  • WSLの破損に備え、WSL上のデータをWindows領域に定期的にバックアップしておきたい。
  • PC自体の破損にも備えるため、バックアップ先をGoogleドライブの同期対象フォルダ内に指定することでクラウドにもバックアップを取りたい。

環境

  • Windows 10
  • WSL2 (Ubuntu 22.04.3 LTS)

同期を実行するシェルスクリプトの作成

以下のようなシェルスクリプトにより、WSL領域のディレクトリをWindows領域に同期することができます。

sync.sh
#!/bin/bash

# WSLのバックアップ対象のディレクトリ
WSL_BACKUP_DIR="/home"

# Windows側のバックアップ先ディレクトリ
WINDOWS_BACKUP_DIR="/mnt/c/Users/user_name/path_to_backup_dir"

# rsyncコマンドを使って同期する
rsync -av --delete --exclude="/home/user_name/.vscode-server" $WSL_BACKUP_DIR $WINDOWS_BACKUP_DIR
  • 同期の対象外とするファイル/ディレクトリは--excludeにより指定できます。
  • Windows側のバックアップ先ディレクトリをGoogleドライブなどのウォッチフォルダ内に指定することで、クラウド上にもバックアップを作成できます。

上記のシェルスクリプトを実行すると、バックアップが実行されます。

$ bash sync.sh

定期的なバックアップの実行設定

作成したシェルスクリプトを定期的に自動で実行するように設定します。ここでは、cronによる設定方法を説明します。

crontabの設定

crontabを開きます。

$ crontab -e

定期実行する内容をcrontabに記載します。以下は、毎時0分にsync.shを実行する場合の例です。

crontab
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

0 * * * * /home/user_name/sh/sync.sh

以下のコマンドにより、crontabの変更内容が反映されていることを確認します。

$ crontab -l
  • 0 * * * *の部分は、毎時0分に実行するようコマンドの実行タイミングを指定しています。左から順に分 時 日 月 曜日を指定しており、例えば* * * * *とした場合には毎分実行されます。

cronの設定など

シェルスクリプトに実行権限を与えます。

$ chmod +x /home/user_name/sh/sync.sh

cronが実行されていることを確認します。

$ service cron status

* cron is runningと表示されればOKです。cronが起動しておらずcron is not runningと表示される場合、以下により起動します。

$ sudo service cron start

crontabの変更内容を反映するため、cronを再起動します。

$ sudo service cron restart

これでsync.shの自動定期実行が設定できました。

4
5
0

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
4
5