通过管道向 hadoop put 文件

来源:互联网 发布:钱夫人淘宝店真实销量 编辑:程序博客网 时间:2024/05/16 08:15


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

Shell 代码
  1. cd $HADOOP_HOME  
  2. bin/hadoop fs -put localfile $hdfsFile  
  3. bin/hadoop fs -put localfiles $hdfsDir  
cd $HADOOP_HOMEbin/hadoop fs -put localfile $hdfsFilebin/hadoop fs -put localfiles $hdfsDir

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

Shell代码
  1. cd $HADOOP_HOME  
  2. if bin/hadoop fs -test -d $hdfsFile  
  3. then  
  4.     echo "$hdfsFile is a directory" >&2  
  5.     exit 1  
  6. fi  
  7. cat localfileS | bin/hadoop fs -put /dev/fd/0  $hdfsFile  
  8. if [[ "0 0" == ${PIPESTATUS[*]} ]]  
  9. then  
  10.     echo success  
  11. else  
  12.     bin/hadoop fs -rm $hdfsFile  
  13.     echo failed >&2  
  14. fi   
cd $HADOOP_HOMEif bin/hadoop fs -test -d $hdfsFilethen    echo "$hdfsFile is a directory" >&2    exit 1ficat localfileS | bin/hadoop fs -put /dev/fd/0  $hdfsFileif [[ "0 0" == ${PIPESTATUS[*]} ]]then    echo successelse    bin/hadoop fs -rm $hdfsFile    echo failed >&2fi 

其中,使用 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) 。


2014-01-19:不知道从什么时候开始,hadoop fs -put 可以使用 '-' 代表 stdin,不再需要使用 /dev/fd/0

原创粉丝点击