通过管道向 hadoop put 文件

使用 hadoop file shell 可以方便地向 hdfs put 文件,但是,该 shell 不支持从管道读取数据并放到 hdfs 文件中。它仅支持这样的 put 命令:

cd $HADOOP_HOME
bin/hadoop fs -put localfile $hdfsFile
bin/hadoop fs -put localfiles $hdfsDir

 幸好,主流的 unix (linux,bsd等)都有一个 /dev/fd/ 目录,可以用它实现从管道 put 文件

cd $HADOOP_HOME
if bin/hadoop fs -test -d $hdfsFile
then
    echo "$hdfsFile is a directory" >&2
    exit 1
fi
cat localfileS | bin/hadoop fs -put /dev/fd/0  $hdfsFile
if [[ "0 0" == ${PIPESTATUS[*]} ]]
then
    echo success
else
    bin/hadoop fs -rm $hdfsFile
    echo failed >&2
fi 

其中,使用 PIPESTATUS 检查错误

 

需要注意,使用 /dev/fd/0 put 文件时,hdfsFile 必须事先不存在,并且不能是一个目录,如果hdfsFile实际上是一个目录,那么,put 仍然正确执行,但是,hdfs 中的文件名将是 hdfsFile/0

 

/dev/fd/ 中是进程所有已打开的文件描述符列表,例如 /dev/fd/0 代表标准输入,/dev/fd/1 代表标准输出,/dev/fd/2 代表标准错误输出,等等,打开 /dev/fd/n 相当于调用 dup(n) 。

你可能感兴趣的:(linux,hadoop,unix)