在Linux文件系統中,我們可以使用下面shell腳本判斷某個文件是否存在:
# 這里的-f參數判斷$file是否存在
if [ ! -f "$file" ]; then
echo "文件不存在!"
fi
但是我們想判斷hdfs上某個文件是否存在咋辦呢?Hadoop內置提供了判斷某個文件是否存在的命令:
在linux文件系統中,我們可以使用下面shell腳本判斷:
if [ ! -f "$file" ];then
echo "文件不存在"
fi
同樣hadoop內置了提供了判斷某個文件是否存在的命令
hadoop fs -test
-d 判斷<path>是否是目錄
-e 判斷<path>是否存在
-f 判斷<path>是否是個文件
-s 判斷內容是否大於0bytes ,大於0為真
-z 判斷內容是否等於0bytes,為0真
從上面的輸出可以看出,我們可以使用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