linux - 在 bash 脚本中发出 pushd 命令后,readlink 命令行为异常

标签 linux bash shell readlink

我遇到了一个复杂的问题,我试着用下面的简单例子来解释它

在我的系统中我有

ubuntu@ubuntu:~/temp$ pwd
/home/ubuntu/temp
ubuntu@ubuntu:~/temp$ ls
temp1  test.sh
ubuntu@ubuntu:~/temp$ 

在 temp.sh 我有

#!/bin/bash

echo "Arg 0 = $0"
echo "Arg 1 = $1"
echo "Arg 0 Full Path $(readlink -f $0)"
echo "Arg 1 Full Path $(readlink -f $1)"
pushd /var/log
echo "Arg 0 = $0"
echo "Arg 1 = $1"
echo "Arg 0 Full Path $(readlink -f $0)"
echo "Arg 1 Full Path $(readlink -f $1)"

现在我在下面跑

ubuntu@ubuntu:~/temp$ ./test.sh temp1
Arg 0 = ./test.sh
Arg 1 = temp1
Arg 0 Full Path /home/ubuntu/temp/test.sh
Arg 1 Full Path /home/ubuntu/temp/temp1
/var/log ~/temp
Arg 0 = ./test.sh
Arg 1 = temp1
Arg 0 Full Path /var/log/test.sh
Arg 1 Full Path /var/log/temp1

在这里您可以看到 readlink 在发出 pushd 命令后显示了错误的 Arg0 和 Arg1 文件路径。 如果我删除 popd 命令,那么它打印正常。

那么为什么这里的 readlink 行为不端?

最佳答案

给定相对路径,readlink 将相对于进程工作目录解释它们,并输出绝对路径(解析中间的符号链接(symbolic link))。

这里的关键点是进程工作目录(又名当前目录)。

所以 readlink ./path/to/file 将输出 /tmp/path/to/file 如果 /tmp 是当前目录(假设没有符号链接(symbolic link))。

您正在使用的另一个命令 pushd 将更改进程工作目录。

所以顺序

readlink ./path/to/file
pushd /some/other/place
readlink ./path/to/file

readlink 都可能解析为两个不同的绝对路径。

这里没有不当行为。一切由设计决定。

关于linux - 在 bash 脚本中发出 pushd 命令后,readlink 命令行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37815276/

相关文章:

linux - 如何获取Linux "at"命令创建的作业数量

php - 如何在 php 中使用 sudo 以 root 用户身份访问服务器

linux - 为新的 Hadoop 集群自动配置 SSH

macos - 如何让shell脚本等待pkg完成安装

linux - 几天前显示所有修改文件的Shell脚本

bash - 获取 shell 脚本错误的行号

java - 如何在 Linux 中删除/tmp/.java_pid<number> 文件?

linux - 使用 .htaccess 阻止来自 Google bot 的文件夹

R:使用 system() 调用的别名命令

shell - 使用 sed 更新特定字段