我有安装了 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
使文件可执行
输出总是不存在
最佳答案
由于您编写了 "~/.config"
,它将被视为文字字符串。为了允许 ~
shell 扩展,你需要不加引号:
#!/bin/bash
if [ -d ~/.config ] ; then
echo "Directory exist"
else
echo "Does not exist"
fi
Bash Pitfals, 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"`
关于linux - 如果 bash 脚本的条件有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53341654/