linux - 如果 bash 脚本的条件有什么问题

标签 linux bash

我有安装了 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/

相关文章:

bash - 捕获远程 ssh 命令失败的输出

linux - 我可以用什么来捕获我在 bash 中运行的每个命令(a-la 历史)

python - 从python访问没有-fPIC编译的库

c - 父子进程两个描述符之间管道创建查询

c - inotify 是否同步排队事件?

linux - bash 无法识别两位数

python - 无法在python中导入模块

linux - 在 Linux 上的 lldb 中打开 .NET Core 2.0 转储 - 哪个 lldb 版本?

perl - 如何使用 AWK 或 sed 或 Perl 进行此类替换?

linux - 通过shell脚本更改文本文件中的路径地址