Bash 遍历字符串列表

mic*_*con 6 bash shell-script text-processing busybox

我有这个 bash 脚本:

for opt in string1 string2 string3 ... string99
do somestuff
Run Code Online (Sandbox Code Playgroud)

它有效,但我想用一个实际包含所有字符串的文件替换我的字符串的显式列表;像这样:

strings=loadFromFile
for opt in $strings
do somestuff
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

IBB*_*ard 10

while read VAR在这里可能是最好的,因为它处理每行输入。您可以从文件重定向它,例如:

while IFS= read -r THELINE; do
  echo "..$THELINE"
done </path/to/file
Run Code Online (Sandbox Code Playgroud)

这会给你每一行以“..”开头

对于您的示例案例:

while IFS= read -r opt; do
  #somestuff $opt
done </path/to/file
Run Code Online (Sandbox Code Playgroud)

请参阅为什么经常使用 `while IFS= read`,而不是 `IFS=; 阅读时..`?为解释。

  • 从内存管理的角度来看,将猫放入管道是不好的行为。特别是在使用“过滤器”内置命令时。@rush 的答案更好,而且我每天都在使用它。 (3认同)
  • 它还将 `while` 循环放入子 shell,如果更新循环中的变量值,这可能会导致混淆行为(当子 shell 退出时,这些值将消失) (3认同)

rus*_*ush 7

while IFS= read -r opt
do 
    some_stuff
done < file_with_string
Run Code Online (Sandbox Code Playgroud)

请参阅为什么经常使用 `while IFS= read`,而不是 `IFS=; 阅读时..`?为解释。