这是我正在处理的 bash 脚本:
dir="~/path/to/$1/folder"
if [ -d "$dir" ]; then
# do some stuff
else
echo "Directory $dir doesn't exist";
exit 1
fi
当我从终端运行它时:
> ./myscript.sh 123 Directory ~/path/to/123/folder doesn't exist
但该文件夹显然确实存在。这可以正常工作:
> ls ~/path/to/123/folder
我做错了什么?
最佳答案
问题在于 bash 在 shell 参数替换之前执行波浪号扩展,因此在将 ~/path/to/folder
替换为 $dir
后,它不会尝试展开~
,因此它会查找一个字面上用波浪号命名的目录,当然该目录不存在。请参阅section 3.5 of the bash manual有关 bash 扩展的更详细说明。
关于bash - 使用 Bash 脚本检查目录是否存在的奇怪错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/973093/