繁体   English   中英

如何遍历shell中的列表?

[英]How to loop through a list in shell?

假设我有一个输出字符串列表的命令

string1
string2
string3
.
.
stringN

如何在 shell 中循环遍历列表的输出?

例如:

myVal=myCmd
for val in myVal
  do
    # do some stuff
  end

使用bash while-loop ,循环可以通过命令或输入文件完成。

while IFS= read -r string
do 
    some_stuff to do
done < <(command_that_produces_string)

举个例子,我有一个包含内容的示例文件

$ cat file
My
name
is not 
relevant
here

我修改了脚本以在它读取文件时回显该行

$ cat script.sh
#!/bin/bash
while IFS= read -r string
do
    echo "$string"
done < file

./script.sh运行时产生 o/p

My
name
is not
relevant
here

同样也可以通过 bash 命令完成,我们采用process-substitution ( <() )在子 shell 上运行命令。

#!/bin/bash

while IFS= read -r -d '' file; do
    echo "$file"
done < <(find . -maxdepth 1 -mindepth 1 -name "*.txt" -type f -print0)

上面的简单find列出了当前目录中的所有文件(包括带有空格/特殊字符的文件)。 在这里, find命令的输出被馈送到由while-loop解析的stdin

您非常接近,无法判断是否只是剪切和粘贴/错别字导致了问题 - 请注意第 1 行的引号和第 2 行的 $。

myVal=`echo "a b c"`
for val in $myVal
do
    echo "$val"
done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM