2013-09-25 66 views
1

GNU coreutils命令readlink -f的等效Perl命令是什麼?與readlink具有相同行爲的Perl命令?

如果除了最後一個文件名的任何組分被丟失或不可用,的readlink不產生 輸出和以非零退出代碼退出。尾隨斜槓 被忽略。

+0

注意:readlink不是bash的一部分。 –

+0

@KolyolyHorvath感謝您的澄清。 – 719016

回答

8

您可以使用Cwd

use Cwd 'abs_path'; 
my $path = "/some/arbitrary/path"; 
print abs_path($path); 

測試:

for q in exists imaginary imarginary/imaginary ; do 
    echo "$q" 
    echo -n "readlink -f: " ; readlink -f "$q" 
    echo -n "abs_path: " ; perl -MCwd=abs_path -E'say abs_path $ARGV[0]' "$q" 
    echo 
done 

輸出:

exists 
readlink -f: /home/eric/exists 
abs_path: /home/eric/exists 

imaginary 
readlink -f: /home/eric/imaginary 
abs_path: /home/eric/imaginary 

imaginary/imaginary 
readlink -f: abs_path: 
+0

謝謝,我想確保Perl中的'Cwd abs_path'和GNU coreutils'readlink -f'具有相同的行爲。 – 719016

+0

@ 200508519211022689616937是的。 – devnull

+0

有一個錯誤。我修復了它並添加了一個測試。請注意,'abs_path'的行爲可能因系統類型而異。 (您應該在所有unixy系統上獲得相同的行爲。) – ikegami

0

作爲一個總的Perl新人,我很高興地說我有自己想出了這個STDIN解決方案(經過幾次嘗試後,請記住Perl的學習曲線被稱爲陡峭)。 devnull的解決方案是偉大的,沒有疑問,但它是一個有點太「scriptish」對我的口味 - 而我有時候只是想一個Perl的一行到echo「編串,就像這樣:

echo "/home/user/somesymlinkedpath" | perl -MCwd=abs_path -nle 'print abs_path $_' 

因此,可能有更多的人想知道如何編碼這種管道形式(使perl從STDIN中讀取參數),我決定在這裏發佈它。

相關問題