2013-04-23 60 views
3

想要製作腳本(稱爲getmpoint)什麼將從任何文件名返回掛載點。來自文件名的掛載點 - 便攜的方式

第1的想法,比如:解析輸出形成df或分析fstab並不像看起來那麼容易,因爲例如:

getmpoint ../../../some/path/tmp/somefile 
getmpoint /tmp/somesymlink #and want get the mountpoint where the real file is 
getmpoint/

我必須使用stat(獲取裝置)的一些想法 - 但我迷路了。需要一些指導如何解決這個問題。

另一個問題是,stat命令與Freebsd-statLinux-stat不同。這裏有任何便攜式的方式?

同樣的,怎麼樣:

getmpoint /some/real/path/up/to/here/but/nonexistent_file 

將是很好的獲得只能從路徑掛載點 - 無文件存在 - 所以沒有stat

任何建議? (我可能能夠使腳本自己 - 但需要一些指導如何做...)

回答

2

試試這個:

getmpoint.sh,預計文件名作爲PARAM

#!/bin/bash 

for path 
do 
    orig=$path 

    #find the existing path component 
    while [ ! -e "$path" ] 
    do 
     path=$(dirname "$path") 
    done 

    #get a real file from a symlink 
    [ -L "$path" ] && path=$(readlink "$path") 

    # use "portable" (df -P) - to get all informatons 
    # 512-blocks  Used Available Capacity Mounted on 
    read s512 used avail capa mounted <<< $(df -P "$path" | awk '{if(NR==2){ print $2, $3, $4, $5, $6}}') 

    echo "Filename: $orig" 
    echo "Mounted: $mounted" 
    echo "Available blocks: $avail" 
done 
+0

謝謝!好的解決方案和便攜式。 – jm666 2013-04-23 22:08:28

+0

嘿嘿,不錯的編輯:)如果可以的話,會提高它;)。請注意,我第一次嘗試類似'df ... |尾巴-n 1',並驚訝於這沒有奏效。然而'sed'1d''應該可以工作,儘管我更喜歡'awk'解決方案,因爲它給了你第六列(掛載)而不需要額外的解析工作 – hek2mgl 2013-04-23 22:09:47

+0

是的 - 當文件名包含空格時,回到awk :) – jm666 2013-04-23 22:41:12