从嵌套脚本bash回显到文件

时间:2013-12-08 07:13:20

标签: bash

我是bash的新手。我有两个脚本 - script1遍历目录,其中的每个文件都在文件上执行script2。

SCRIPT1:

#!/bin/bash
for file in $(find ../myFiles/ -type f); do
   $( cat $file | ./script2) >> res.txt
done

SCRIPT2:

while read line;
do   ...
  ....
  echo "$line"
done

但是脚本2中的echo "$line"不能正常工作(对于res.txt文件),但是它作为命令输出,导致错误(“找不到命令”)

有人知道怎么做吗? 谢谢。

3 个答案:

答案 0 :(得分:1)

完全按照您的描述,

$( foo )执行命令foo的结果。做:

./script2 < "$file" >> res.txt

没有必要创建一个管道,运行的东西就是bash所做的。 “echo”是一个外部命令。 “[”(如:if [ thing ])也是如此,但实际上bash会在内部处理这些内容。您仍然可以将[作为独立程序运行。输入:which [即可查看。

编辑:,如果不够清楚:

#!/bin/bash
for file in $(find ../myFiles/ -type f); do
    ./script2 < "$file" >> res.txt
done

答案 1 :(得分:0)

如果您使用函数进行处理,任务会更容易:

#!/bin/bash                                                                      

search_path='.'                                                                  

### declare functions ###                                                        
function foo {                                                                   
  for file in `find $search_path -type f`                                        
  do                                                                             
    echo 'processing: '$file                                                     
    process_file $file                                                           
  done                                                                           
}                                                                                

function process_file {                                                          
  while read line                                                                
  do                                                                             
    echo $line                                                                   
  done < $file                                                                   
}                                                                                

### call your main function ###                                                  
foo

如果您以后需要额外的功能,它更容易阅读和修改。 一个脚本也足够了。

(很酷的是,脚本会自行打印。)

答案 2 :(得分:0)

$(...)用于命令替换。请考虑以下脚本:

<强> SCRIPT1:

#!/bin/bash
while read file; do
   ./script2 "$file" >> res.txt
done < <(find . -name "file" -type f)

<强> SCRIPT2:

#!/bin/bash
while read line; do
  echo "$line"
done < "$1"