BASH 找不到使用 ~/in 路径存在的隐藏文件

标签 bash hidden-files

我有一个 BASH 脚本,它正在我的主目录中寻找一个隐藏文件。当我在尝试查找文件时指定绝对路径 /home/user/.foo 然后脚本会找到它但是如果我使用 ~/.foo 然后脚本找不到文件。有人可以解释为什么会发生这种情况以及我可以通过其他什么方式找到该文件。我希望能够在不同用户的主目录中找到该文件,而不仅仅是我自己的主目录。

很抱歉没有提供代码片段,但这里是

file="~/.foo"

[ -f $file ] && echo "foo 存在!"

然而这有效

file="home/user/.foo"

[ -f $file ] && echo "foo 存在!"

最佳答案

这是因为当波浪号是单词中的第一个未加引号的字符时,shell 只执行波浪号扩展。在

file="~/.foo"

波浪号用双引号引起来,因此未展开。最佳做法是始终使用 $HOME 当波浪号应该扩展到您的主目录(而不是像 ~user 中那样的其他用户的主目录。

来自 POSIX 的纯正涂料:

2.6.1 Tilde Expansion

A "tilde-prefix" consists of an unquoted <tilde> character at the beginning of a word, followed by all of the characters preceding the first unquoted <slash> in the word, or all the characters in the word if there is no <slash>. In an assignment (see XBD Variable Assignment), multiple tilde-prefixes can be used: at the beginning of the word (that is, following the <equals-sign> of the assignment), following any unquoted <colon>, or both. A tilde-prefix in an assignment is terminated by the first unquoted <colon> or <slash>. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the <tilde> are treated as a possible login name from the user database. A portable login name cannot contain characters outside the set given in the description of the LOGNAME environment variable in XBD Other Environment Variables. If the login name is null (that is, the tilde-prefix contains only the tilde), the tilde-prefix is replaced by the value of the variable HOME. If HOME is unset, the results are unspecified. Otherwise, the tilde-prefix shall be replaced by a pathname of the initial working directory associated with the login name obtained using the getpwnam() function as defined in the System Interfaces volume of POSIX.1-2008. If the system does not recognize the login name, the results are undefined.

The pathname resulting from tilde expansion shall be treated as if quoted to prevent it being altered by field splitting and pathname expansion.

关于BASH 找不到使用 ~/in 路径存在的隐藏文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31935839/

相关文章:

linux - Linux bash 递归函数的返回值

bash - 从 Bash 中的行中删除中间的 n 个字符

bash - 带有参数的可覆盖预定义 Bash 变量

c# - 如何通过https获取隐藏文件的内容?

Bash + sed/awk/cut 删除第 n 个字符

macos - sudo open -e ~/.bash_profile Permission denied mac

bash - 如何在 Bash 中创建隐藏文件

python - 操作系统错误 : [Errno 20] Not a directory, .DS_Store

php - 从 scandir 中排除隐藏文件