2015-04-24 72 views
1

From superuser這個os x bash腳本如何模擬linux的readlink工作?

function abspath() { 
    pushd . > /dev/null; 
    if [ -d "$1" ]; then 
    cd "$1"; 
    dirs -l +0; 
    else 
    cd "`dirname \"$1\"`"; 
    cur_dir=`dirs -l +0`; 
    if [ "$cur_dir" == "/" ]; then 
     echo "$cur_dir`basename \"$1\"`"; 
    else 
     echo "$cur_dir/`basename \"$1\"`"; 
    fi; 
    fi; 
    popd > /dev/null; 
} 

我想使用這個劇本,但我謹慎使用的東西,我不完全理解的。

+2

你需要找到函數'dirs'來知道它做了什麼。 –

+1

您還可以將每行/每段代碼複製/粘貼到終端窗口中。使用'set -x'來顯示變量的擴展。使用'set - 「/ your/dir/of/interest」'爲'$ 1'設置一個值。祝你好運。 – shellter

+1

另外,編寫一個相當於'readlink'命令的程序並不難,也不難獲得'readlink'的GNU版本並將其安裝到Mac上。 –

回答

2

除了小細節,它並沒有真正句法語義也仿效readlink(1)/stat(1)命令,你會得到所有你通過調用man bash並搜索dirspushd想要的信息,並在其中popd內置文檔。 basenamedirname命令也有各自的手冊頁,它們比我想象的更好地解釋了命令的功能。

話雖如此,我們先描述一下你提到有些腳本:

1 function abspath() { 
2 pushd . > /dev/null; 
3 if [ -d "$1" ]; then 
4  cd "$1"; 
5  dirs -l +0; 
6 else 
7  cd "`dirname \"$1\"`"; 
8  cur_dir=`dirs -l +0`; 
9  if [ "$cur_dir" == "/" ]; then 
10  echo "$cur_dir`basename \"$1\"`"; 
11  else 
12  echo "$cur_dir/`basename \"$1\"`"; 
13  fi; 
14 fi; 
15 popd > /dev/null; 
16 } 

幾點說明:

 
1) Define a shell function 
2) Add current working directory to the directory stack and change to it 
3) If the submitted parameter corresponds to a directory 
4) Change to it 
5) Show full pathname of the current working directory 
6) otherwise [if the submitted parameter is not a directory] 
7) strip away the filename portion, beginning with the last slash `/' character to the end of string and change into the directory 
8) Store the full pathname of the current working directory into the `cur_dir` variable 
9) if the current working directory is '/' then 
10) output the full qualified path using the cur_dir variable and the base name of the submitted parameter 
11) otherwise 
12) output the full qualified path using the cur_dir variable, a `/', and the base name of the submitted parameter 
13) end of inner if block 
14) end of outer if block 
15) remove current working directory from directory stack and change back it, essentially moving back to the originating directory from where we called the function from. 
16) close shell function definition 
與手冊頁和相應的bash的內置文檔

在一起,你應該明白的內部運作這個shell函數。