2016年5月30日 星期一

[Linux 常見問題] Bash: How to read one line at a time from output of a command?

Source From Here
Question
I am trying to read the output of a command in bash using a while loop:
- test.sh
  1. #!/bin/bash  
  2. while read -r line  
  3. do  
  4.     echo "$line"  
  5. done <<< $(find . -type f)  
The output I got:
# ./test.sh
./DebugPy.py ./DebugPy.pyc ./zombe.py ./test.sh

After this I tried:
- test2.sh
  1. #!/bin/bash  
  2. $(find . -type f) |  
  3. while read -r line  
  4. do  
  5.     echo "$line"  
  6. done  
but it generated an error "Error: Must provide process id to debug" So, how do I read it line by line because I think currently it is slurping the entire line at once.

How-To
There's a mistake, you need < <(command) not <<<$(command)< <( ) is a Process Substitution$() is a command substitution and <<< is a here-string. So you can do it this way:
- test3.sh
  1. #!/bin/bash  
  2. find . -type f |  
  3. while read -r line; do  
  4.   echo "$line"  
  5. done  
The execution result:
# ./test3.sh
./DebugPy.py
./DebugPy.pyc
./test3.sh
./test2.sh
./zombe.py
./test.sh
Another approach using Process Substitution:
- test4.sh
  1. #!/bin/bash  
  2. while read -r line; do  
  3.     echo "$line"  
  4. done < <(find . -type f)  
Some advantages of process substitution:
* No need to save temporary files.
* Better performance. Reading from another process often faster than writing to disk, then read back in.
* Save time to computation since when it is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...