如果 test -d 没有找到 ~/ 目录

if test -d doesn't found ~/ directory

我正在做 script.sh,我必须知道目录是否存在。但是,当我尝试访问以检查我的文件夹文档(在我的主目录中)时,如果我使用相对路径 ~/Documents 它不起作用。这是我的代码:

function checkDirectory {
    read directory
    if test -d $directory
        then
            echo "exists"
        else echo "doesn't exists"
    fi
 }
 checkDirectory

我已经尝试过 if test -d $directory 和 if test -d "$directory"。我还尝试先将我的工作目录更改为“/”。

有趣的是,当我将相对路径用作 ../ 时,它起作用了!而且,更奇怪的是,写在 shell 上的相同代码而不是通过 我的脚本文件也能正常工作。

我在 Mac 和 Ubuntu 上检查过这个。

我一直在寻找答案,但我发现的只是在 shell 上执行 if 测试,或者使用其他语言或使用相对路径而不是 ~/.

有人知道我想念什么吗?

谢谢。

问题是 test -d 不理解波浪字符 ~。要解决此问题,您可以这样做:

[STEP 101] # read dir
~/tmp
[STEP 102] # eval "dir=$dir"
[STEP 103] # test -d "$dir" && echo yes
yes
[STEP 104] #

您应该更正您的脚本以使用一些参数(例如 </code>)而不是 <code>read-ing,然后 运行

 checkDirectory ~

 checkDirectory $HOME

您需要 ~globbed by your shell. You may do the globbing in your script (e.g. with eval if you insist on read-ing a variable) ; read glob(7)

谨防恶意 code injections(例如用户键入 foo; rm -rf $HOME

阅读advanced bash scripting guide

您需要使用 eval 评估从 read 命令读取的 ~,如下所示:

function checkDirectory {
    read directory
    if test -d "`eval echo ${directory//>}`"
        then
            echo "exists"
        else echo "doesn't exists"
    fi
 }
 checkDirectory

您可能会注意到代码中有一个额外的 //>,用于转义命令中的任何 space 和输出重定向 > 以防止手头执行。

编辑:

回答您的评论:

如果您将输入重定向到某个文件,例如:

checkDirectory.sh
>>  ~/directory name/path/ > file1.txt

您的目录名称 directory name 中有一个 space。并且您正在使用重定向运算符 >.

将命令的输出传递到文件 file1.txt