How to check if a location is a btrfs subunit?

In bash scripts, how can I check elegantly if the specific location is subvolume btrfs?

I DO NOT want to know if this location is on the btrfs (or subvolume) file system. I want to know if a given location is a subvolume header.

Ideally, the solution could be written in the bash function, so I could write:

if is_btrfs_subvolume $LOCATION; then # ... stuff ... fi 

An โ€œelegantโ€ solution would be readable, small in code, and low resource consumption.

+5
source share
2 answers

Solution1: Using @kdave's suggestions:

 is_btrfs_subvolume() { local dir=$1 [ "$(stat -f --format="%T" "$dir")" == "btrfs" ] || return 1 inode="$(stat --format="%i" "$dir")" case "$inode" in 2|256) return 0;; *) return 1;; esac } 

Solution2: What I used before (only one call, but probably fragile):

 is_btrfs_subvolume() { btrfs subvolume show "$1" >/dev/null 2>&1 } 

EDIT: Fixed and replaced list with show , since list behavior would not respond correctly in any regular btrfs directory.

EDIT2: since @kdave did not post the full version of his excellent answer, I added it to my answer.

+3
source

Subvolume is identified by an inode of 256, so you can check it simply

 if [ `stat --format=%i /path` -eq 256 ]; then ...; fi 

There is also the so-called empty-subvolume, i.e. if the nested subselects are removed, this object will exist instead of the original subselect. Its inode number is 2.

For a common check, if any directory is subvolume, the file system type must also be checked.

 stat -f --format=%T /path 
+10
source

Source: https://habr.com/ru/post/1202854/


All Articles