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

Kin*_*arō 1 bash shell

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

string1
string2
string3
.
.
stringN
Run Code Online (Sandbox Code Playgroud)

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

例如:

myVal=myCmd
for val in myVal
  do
    # do some stuff
  end
Run Code Online (Sandbox Code Playgroud)

Ini*_*ian 5

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

while IFS= read -r string
do 
    some_stuff to do
done < <(command_that_produces_string)
Run Code Online (Sandbox Code Playgroud)

举个例子,我有一个示例文件,其内容为

$ cat file
My
name
is not 
relevant
here
Run Code Online (Sandbox Code Playgroud)

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

$ cat script.sh
#!/bin/bash
while IFS= read -r string
do
    echo "$string"
done < file
Run Code Online (Sandbox Code Playgroud)

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

My
name
is not
relevant
here
Run Code Online (Sandbox Code Playgroud)

同样的事情也可以通过 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)
Run Code Online (Sandbox Code Playgroud)

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