Shell中判斷HDFS中的檔案或目錄是否存在
阿新 • • 發佈:2018-12-21
在Linux檔案系統中,Shell指令碼判斷某個檔案是否存在:
# 這裡的-f引數判斷$file是否存在
if [ ! -f "$file" ]; then
echo "檔案不存在!"
fi
Hadoop提供了test
命令判斷HDFS上某個檔案或目錄是否存在:
[[email protected] ~]# hdfs dfs -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] ~]# hdfs dfs -test -e /path/not/exist
[[email protected] ~]# echo $?
1
[[email protected] ~]# hdfs dfs -test -e /path/exist
[[email protected] ~]# echo $?
0
[[email protected] ~]#
那麼我們可以在Shell腳本里面判斷HDFS上某個檔案是否存在:
#!/bin/bash
hdfs dfs -test -e /path/exist
if [ $? -eq 0 ] ;then
echo 'exist'
else
echo 'Error! NO Such File Or Directory !'
fi
...
test
命令還可以判斷:**
-d
某個路徑是否是資料夾( -d);-f
某個路徑是否是檔案( -f);-s
某個檔案大小是否大於0;-z
某個檔案大小等於0
#!/bin/bash
#判斷是否是資料夾
hdfs dfs -test -d /path/exist
if [ $? -eq 0 ] ;then
echo 'Is a directory'
else
echo 'Is not a directory'
fi
#判斷是否是檔案
hdfs dfs -test -f /path/exist
if [ $? -eq 0 ] ;then
echo 'Is a file'
else
echo 'Is not a file'
fi
#判斷檔案大小是否大於0
hdfs dfs -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
#判斷檔案大小是否等於0
hdfs dfs -test -z /path/exist
if [ $? -eq 0 ] ;then
echo 'Is zero bytes in size.'
else
echo 'Is not zero bytes in size. '
fi