在shell中如何判斷HDFS中的文件目錄是否存在

Linux文件系統中,我們可以使用下面的Shell腳本判斷某個文件是否存在:

# 這裏的-f參數判斷$file是否存在

if [ ! -f "$file" ]; then

  echo "文件不存在!"

fi

但是我們想判斷HDFS上某個文件是否存在咋辦呢?別急,Hadoop內置提供了判斷某個文件是否存在的命令:

[[email protected] ~]$ 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。

[[email protected] ~]$ hadoop fs -test -e /path/not/exist

[[email protected] ~]$ echo $?

1

 

[[email protected] ~]$ hadoop fs -test -e /path/exist

[[email protected] ~]$ echo $?

0

所以我們可以在Shell裏面判斷HDFS上某個文件是否存在:

hadoop fs -test -e /path/exist

if [ $? -eq 0 ] ;then 

    echo 'exist' 

else 

    echo 'Error! path is not exist' 

fi 

test命令還可以判斷某個文件是否是文件夾、是否是文件、某個文件大小是否大於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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章