
私は与えられたファイルを含むファイルシステムのマウントポイントを見つけるための簡単な方法を探しています。以下の解決策よりもシンプルでシンプルなものはありますか?
df -h FILE |tail -1 | awk -F% '{print $NF}' | tr -d ' '
エマルジョンディスクマウントの場所を確認する命令がありますか?「ディスク上の任意のファイルではなく、現在のディスクのデバイスノードを入力として使用します...
答え1
stat
GNU/Linux に GNU coreutils 8.6 以降がある場合は、次のことができます。
stat -c %m -- "$file"
それ以外の場合:
mount_point_of() {
f=$(readlink -e -- "$1") &&
until mountpoint -q -- "$f"; do
f=${f%/*}; f=${f:-/}
done &&
printf '%s\n' "$f"
}
あなたのアプローチは有効ですが、マウントポイントにスペース、%、改行、または他の印刷できない文字が含まれていないと仮定すると、df
最新バージョンのGNU(8.21以降)を使用して少し単純化できます。
df --output=target FILE | tail -n +2
答え2
Linuxの場合は、このために作成されたutil-linuxのfindmntがあります。
findmnt -n -o TARGET --target /path/to/FILE
バインドマウントが複数ある場合は、任意のランダムマウントポイントが返されることがあります。使用df
にも同じ問題があります。
答え3
次のようなことができます
df -P FILE | awk 'NR==2{print $NF}'
でも
df -P FILE | awk 'END{print $NF}'
スペースに分割するのがデフォルトなので、スペースを切り捨てたりawk
指定したりする必要はありません。最後に、関心のある行番号()を指定してキャンセルすることもできます。-F
tr
NR==2
tail
答え4
C ++でこれを行うには、ここに追加のC ++コードがあります。
#include <boost/filesystem.hpp>
#include <sys/stat.h>
/// returns true if the path is a mount point
bool Stat::IsMount(const std::string& path)
{
if (path == "") return false;
if (path == "/") return true;
boost::filesystem::path path2(path);
auto parent = path2.parent_path();
struct stat sb_path;
if (lstat(path.c_str(), &sb_path) == -1) return false; // path does not exist
if (!S_ISDIR(sb_path.st_mode)) return false; // path is not a directory
struct stat sb_parent;
if (lstat(parent.string().c_str(), &sb_parent) == -1 ) return false; // parent does not exist
if (sb_path.st_dev == sb_parent.st_dev) return false; // parent and child have same device id
return true;
}
/// returns the path to the mount point that contains the path
std::string Stat::MountPoint(const std::string& path0)
{
// first find the first "real" part of the path, because this file may not exist yet
boost::filesystem::path path(path0);
while(!boost::filesystem::exists(path) )
{
path = path.parent_path();
}
// then look for the mount point
path = boost::filesystem::canonical(path);
while(! IsMount(path.string()) )
{
path = path.parent_path();
}
return path.string();
}
プログラミング方法への追加リンク