gpt4 book ai didi

linux - 这个模拟 linux 的 readlink 的 os x bash 脚本是如何工作的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:06 25 4
gpt4 key购买 nike

From superuser :

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;
}

我想使用这个脚本,但我对使用我不完全理解的东西持谨慎态度。

最佳答案

除了它在语法上和语义上都没有真正模拟 readlink(1)/stat(1) 命令的小细节之外,您将通过调用 man bash 获得所需的所有信息 并在其中搜索 dirspushdpopd 内置文档。 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 parameter11) otherwise12) output the full qualified path using the cur_dir variable, a `/', and the base name of the submitted parameter13) end of inner if block14) end of outer if block15) 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 函数的内部工作原理。

关于linux - 这个模拟 linux 的 readlink 的 os x bash 脚本是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29836821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com