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

標籤

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


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!