这个bash脚本的if条件语句有什么问题?

3

我有安装ZSH的Ubuntu 18.04。我有这个用于检查目录是否存在的bash脚本。

尽管我有一个名为“~/.config”的目录,但条件始终为负。我似乎无法弄清楚我的代码有什么问题。

setup.sh

#!/bin/bash

if [ -d "~/.config" ] ; then
  echo "Directory exist"
else
  echo "Does not exist"
fi

通过使用chmod +x ./setup.sh使文件可执行。 输出始终为不存在

3
~被引用时,它不会扩展到您的主目录。请尝试使用以下命令:[ -d ~/.config ] - user142162
还可以参考以下内容:如何使用Shellcheck如何调试Bash脚本?(U&L.SE)、如何调试Bash脚本?(SO)、如何调试Bash脚本?(AskU)、调试Bash脚本等。 - jww
2个回答

5

由于您写了"~/.config",它将被视为字面字符串。为了允许~ shell扩展,您需要将其保留为未引用的状态:

#!/bin/bash
if [ -d ~/.config ] ; then
  echo "Directory exist"
else
  echo "Does not exist"
fi

这个可以很好地解释为 Bash陷阱,26. echo“~”

26. echo "~"

Tilde expansion only applies when '~' is unquoted. In this example echo writes '~' to stdout, rather than the path of the user's home directory.

Quoting path parameters that are expressed relative to a user's home directory should be done using $HOME rather than '~'. For instance consider the situation where $HOME is "/home/my photos".

"~/dir with spaces" # expands to "~/dir with spaces"
~"/dir with spaces" # expands to "~/dir with spaces"
~/"dir with spaces" # expands to "/home/my photos/dir with spaces"
"$HOME/dir with spaces" # expands to "/home/my photos/dir with spaces"`

谢谢,我尝试了不加双引号的方式,现在可以工作了。 - Eskinder Getahun

2
在bash中,双引号("...")会抑制通配符和相关扩展,例如*~等。
双引号保留shell变量扩展;单引号('...')则同时抑制通配符扩展和shell变量扩展。因此,在不同的上下文中它们各有用处。
但在需要*~等具有特殊含义的上下文中,则需要使用未加引号的表达式。只要小心处理,因为如果不小心,由于扩展可能会发生意外情况。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接