使用 hdfs dfs -test 查看目录是否存在

Lio*_*cer 3 hadoop hdfs

在 hadoop 文档中:

test

Usage: hadoop fs -test -[defsz] URI

Options:

-d: f the path is a directory, return 0.
-e: if the path exists, return 0.
-f: if the path is a file, return 0.
-s: if the path is not empty, return 0.
-z: if the file is zero length, return 0.
Example:

hadoop fs -test -e filename
Run Code Online (Sandbox Code Playgroud)

如果 hdfs 目录不存在,我想做点什么。选项中的每个参数-test都返回 0。如果目录不存在,我如何才能输出?

drwx------   - bli1 hadoop_bips          0 2016-01-29 12:48 /user/bli1/.Trash
drwx------   - bli1 hadoop_bips          0 2016-01-08 09:41 /user/bli1/.staging
drwxr-x---   - bli1 hadoop_bips          0 2015-03-31 09:35 /user/bli1/camus_test
drwxr-x---   - bli1 hadoop_bips          0 2015-11-18 12:41 /user/bli1/hdfs_archive
drwxr-x---   - bli1 hadoop_bips          0 2016-01-26 16:18 /user/bli1/hdfs_archive_archive
drwxr-x---   - bli1 hadoop_bips          0 2016-01-26 16:19 /user/bli1/hdfs_archive_concatenate
drwxr-x---   - bli1 hadoop_bips          0 2016-01-26 16:15 /user/bli1/hdfs_archive_delete
drwxr-x---   - bli1 hadoop_bips          0 2015-03-31 16:20 /user/bli1/output
drwxr-x---   - bli1 hadoop_bips          0 2015-03-29 18:09 /user/bli1/wordcount
Run Code Online (Sandbox Code Playgroud)

我试过这个

$ hdfs dfs -test -d /user/bli1/testdir     # nothing is returned
$
$ hdfs dfs -test -d /user/bli1/output      # nothing is returned
Run Code Online (Sandbox Code Playgroud)

我期待0?我没有看到 0。我没有注意到这两个命令之间有什么不同。

Ana*_*Ana 5

这就是“$?” 做。它存储最后执行的命令的状态。您可以检查它的值。如果是 0,那么,宾果游戏!

target_dir=<dir in hdfs>

hadoop fs -test -d ${target_dir};

if [ $? -eq 0 ]
then 
    echo "Directory exists!"
else
    echo "Directory does not exists!" 
fi
Run Code Online (Sandbox Code Playgroud)