在shell中判断hdfs文件是否存在

在Linux文件系统中,我们可以使用下面shell脚本判断某个文件是否存在:

# 这里的-f参数判断$file是否存在 
if [ ! -f "$file" ]; then
  echo "文件不存在!"
fi

但是我们想判断hdfs上某个文件是否存在咋办呢?Hadoop内置提供了判断某个文件是否存在的命令:

[iteblog@www.iteblog.com ~]$ hadoop fs -help
......
-test -[defsz] <path>:Answer various questions about <path>, with result via exit status.
          -d  return 0 if <path> is a directory.
          -e  return 0 if <path> exists.
          -f  return 0 if <path> is a file.
          -s  return 0 if file <path> is greater than zero bytes in size.
          -z  return 0 if file <path> is zero bytes in size.
        else, return 1.
......

从上面的输出可以看出,我们可以使用test命令来判断某个文件是否存在。如果文件存在,则这个命令将返回0,反之返回1.

[iteblog@www.iteblog.com ~]$ hadoop fs -test -e /path/not/exist
[iteblog@www.iteblog.com ~]$ echo $?
1
 
[iteblog@www.iteblog.com ~]$ hadoop fs -test -e /path/exist
[iteblog@www.iteblog.com ~]$ echo $?
0

所以,上代码:

hadoop fs -test -e /path/exist
if [ $? -eq 0 ] ;then 
    echo 'exist' 
else 
    echo 'Error! path is not exist' 
fi 

除此之外,还可以判断某个文件是否是文件夹、是否是文件、某个文件的大小是否大于0或者等于0。

hadoop fs -test -d /path/exist
if [ $? -eq 0 ] ;then 
    echo 'Is a directory' 
else 
    echo 'Is not a directory' 
fi
  
hadoop fs -test -f /path/exist
if [ $? -eq 0 ] ;then 
    echo 'Is a file' 
else 
    echo 'Is not a file' 
fi
 
hadoop fs -test -s /path/exist
if [ $? -eq 0 ] ;then 
    echo 'Is greater than zero bytes in size' 
else 
    echo 'Is not greater than zero bytes in size' 
fi
 
 
hadoop fs -test -z /path/exist
if [ $? -eq 0 ] ;then 
    echo 'Is zero bytes in size.' 
else 
    echo 'Is not zero bytes in size. '
fi
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 首先,我们在使用前先看看HDFS是什麽?这将有助于我们是以后的运维使用和故障排除思路的获得。 HDFS采用mast...
    W_Bousquet阅读 9,739评论 0 2
  • 沐朝阳之暖,嗅万物之鲜 望山野之雄翰,容百川之浊莠 泻万千思绪之聚倾,省云团雾扰之纷繁 鉴百世沉浮之更迭,看雾里藏...
    暖暖星空阅读 1,878评论 0 0