在Bourne shell中捕获命令输出的标准方法是使用以下$()语法:
output=$(mycommand)
Run Code Online (Sandbox Code Playgroud)
但是,对于具有大量输出的命令,这需要shell将整个内存分配为一个长字符串.我宁愿找到一些与Unix C函数具有道德等价的东西popen,以获得一个新的文件描述符,我可以read:
newfd=popen(mycommand)
while read -u $newfd LINE; do
#process output
done
Run Code Online (Sandbox Code Playgroud)
这甚至可能吗?
小智 7
#!bash
ls | while read X
do
echo $X is a directory entry
done
Run Code Online (Sandbox Code Playgroud)
用您选择的命令替换'ls'