linux - 如何在后台同时使用不同参数的循环运行 bash 脚本中的命令,同时格式化输出

标签 linux bash shell

以下代码片段将在脚本中运行,但每个循环需要很长时间。

#!/bin/bash
….
some_command $A $B $C | awk ‘{print$1}’ | while read -r var1; do
    printf "\n$var1 \n"
    printf "\n"
    other_command $var1
    printf "\n"
done
….

我尝试运行此命令,但 printf 语句将在 other_command 之前运行,该命令用于使输出更具可读性。

#!/bin/bash
….
some_command $A $B $C | awk ‘{print$1}’ | while read -r var1; do
    printf "\n$var1 \n"
    printf "\n"|
    other_command $var1 &
    printf "\n"
done
wait 
….

如果我在循环中仅运行 other_command 和 & ,我会得到所需的结果,但它的可读性不太好。

最佳答案

这个想法是将长时间运行的命令移动到一个函数中,并作为子进程多次调用该函数。这样它们就可以并行运行。在函数内部,命令的输出首先写入局部变量,并且仅在命令完成后一次性打印。

#!/bin/bash

function do_something () {
  local OUTPUT="$(other_command "$var1")"
  printf "\n%s\n\n%s\n" "$1" "$OUTPUT";
}

some_command "$A" "$B" "$C" | while read -r "var1" "_";
do
  do_something "$var1" &
done

wait

请注意,每次调用的输出顺序(可能)都会不同,这是并行执行所固有的。

关于linux - 如何在后台同时使用不同参数的循环运行 bash 脚本中的命令,同时格式化输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35113225/

相关文章:

bash - 将字母数字字符串插入文本文件中的某个单词后(密码/sed/awk)

python - 直接python输出到linux文件

c - 使用 C 参数运行 shell 脚本的安全方法,工作示例

linux - 在重定向的标准输出/标准错误中替换 "^M"*动态*

regex - 使用带有否定前瞻的 grep 不返回任何匹配项

linux - Xubuntu LTS 16.0.4 无法识别 bash 脚本

linux - 如何使用 shell 脚本从 5 个数字中获取最大数字

linux - 根据列对一组数据进行排序

mysql - 安装 OTRS5 时出现 SQL 错误

Linux x86 汇编打印问题