简体   繁体   English

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

[英]Strange error checking if directory exists with Bash script

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? 我究竟做错了什么?

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. 问题是bash在替换shell参数之前执行波浪号扩展,因此在将~/path/to/folder替换为$dir ,它不会尝试扩展~ ,因此它将在目录中查找一个以波浪号命名的目录。它,当然不存在。 See section 3.5 of the bash manual for a more detailed explanation on bash's expansions. 有关bash扩展的详细说明,请参见bash手册的3.5节

尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM