測試 btrfs 子卷是否存在

測試 btrfs 子卷是否存在

我在 bash 過程中遇到問題,該過程應將我舊的 rsync 磁碟備份(和存檔)移植到我未來的 btrfs 快照備份。

我想使用該行:

 # btrfs subvolume snapshot /targetdir/@monthly.9 /targetdir/@monthly.8

如果快照 /targetdir/@monthly.8 不存在 jet ,則會按照我的意願創建它。

但如果 /targetdir/@monthly.8 已經存在,那麼 /targetdir/@monthly.8/@onthly.9 就會被創造。

我在這裡缺少一個存在的測試,比如說:

# [[ -bsnap <snap-path> ]] # =TRUE if <snap-path> exists and is a snap!

我怎樣才能克服這個問題?

答案1

btrfs subvolume snapshot …我想如果存在的話你不想運行/targetdir/@monthly.8,無論它是什麼。只需測試它是否存在:

[ -e /targetdir/@monthly.8 ]

或不存在

[ ! -e /targetdir/@monthly.8 ]

什麼更有用。如果它在不應該存在的時候存在,那麼btrfs subvolume delete它就存在。只有當此命令返回時,ERROR: not a subvolume才需要擔心該物件是什麼。我建議您以@monthly.8只能是子磁碟區的方式組織您的工作流程、子磁碟區、安裝點、目錄及其權限。


但如果你真的需要知道

btrfs subvolume show /targetdir/@monthly.8

如果是子卷就會成功;否則它會失敗。例子:

btrfs subvolume show /targetdir/@monthly.8 &>/dev/null && echo "It's a subvolume!"

答案2

@Kamil Maciorowski 的回答很好。但讓我專注於存在性測驗。

假設我正在調試,我需要重複嘗試,並且目標快照已經存在。然後我非常謹慎地坐了“bash -e”(即第一個錯誤退出我的 shell。記住我必須以 root 身份運行它......)。然後我更喜歡一個命令來告訴我發生了什麼,然後退出。因此我這樣做:

    btrfs subvolume list  /targetdir/@monthly.9 | grep @monthly.8 &&  echo "$0 ERROR: snapshot /targetdir/@monthly.8 exists already!" && exit

命令“subvolume list”不會給出錯誤並列出所有內容。然後我根據需要進行篩選並做出決定。

答案3

function btrfsCreateSVIfNotExist ()
{
    # parameters: $1 the dest/name of the subvolume (what you'd pass to btrfs subvolume create, e.g. /home/MYSUBVOLNAME)
    # creates a btrfs subvolume under dest/ if it doesn't already exist
    if ! btrfs subvolume show "$1" > /dev/null 2>&1; then
        btrfs subvolume create "$1"
    fi
}
export -f btrfsCreateSVIfNotExist

相關內容