奇怪的错误检查目录是否存在Bash脚本

时间:2022-01-05 11:29:26

Here's a bash script I'm working on:

这是我正在研究的bash脚本:

dir="~/path/to/$1/folder"

if [ -d "$dir" ]; then
    # do some stuff
else
    echo "Directory $dir doesn't exist";
    exit 1
fi

and when I run it from the terminal:

当我从终端运行它时:

> ./myscript.sh 123
Directory ~/path/to/123/folder doesn't exist

But that folder clearly does exist. This works normally:

但该文件夹显然确实存在。这通常有效:

> ls ~/path/to/123/folder

What am I doing wrong?

我究竟做错了什么?

2 个解决方案

#1


try:

dir="$HOME/path/to/$1/folder"

#2


The problem is that bash performs tilde expansion before shell parameter substitution, so after it substitutes ~/path/to/folder for $dir, it doesn't try to expand the ~, so it looks for a directory literally named with a tilde in it, which of course doesn't exist. See section 3.5 of the bash manual for a more detailed explanation on bash's expansions.

问题是bash在shell参数替换之前执行代码扩展,所以在将$ / path / to / folder替换为$ dir之后,它不会尝试扩展〜,所以它会查找一个字面上以代字号命名的目录它,当然不存在。有关bash扩展的更详细说明,请参阅bash手册的第3.5节。

#1


try:

dir="$HOME/path/to/$1/folder"

#2


The problem is that bash performs tilde expansion before shell parameter substitution, so after it substitutes ~/path/to/folder for $dir, it doesn't try to expand the ~, so it looks for a directory literally named with a tilde in it, which of course doesn't exist. See section 3.5 of the bash manual for a more detailed explanation on bash's expansions.

问题是bash在shell参数替换之前执行代码扩展,所以在将$ / path / to / folder替换为$ dir之后,它不会尝试扩展〜,所以它会查找一个字面上以代字号命名的目录它,当然不存在。有关bash扩展的更详细说明,请参阅bash手册的第3.5节。