如何执行并行命令

How to execute parallel commands

我在做一个大项目,我们有多个 npm packages

我想并行安装所有软件包,这意味着我希望同时 运行 所有软件包(以节省时间),并在最后一次安装完成后继续我的脚本。

示例脚本:

#!/bin/zsh
#...

NPM_FOLDERS=(
    common.library/audit
    common.library/cipher
    common.library/logger
    ...
)

# Get the number of total folders to process
counter=${#NPM_FOLDERS[@]};

# counter for user feedback to the current install folder index
index=1;

# loop and install all the required packages
for folder in $NPM_FOLDERS;
do 
    #  Print the installation message with the folder & couters
    echo "3[38;5;255m($index/$counter) Executing npm install in: 3[38;5;226m$folder";
    
    # change the folder to the required location    
    cd $ROOT_FOLDER/$folder;
    
    # Execute install on this folder
    npm install ;
   
    # increase current index
    let index++;

done

echo
echo "3[38;5;11mInstallation completed."
echo 

我不会接受最快的答案,而是会做我想做的事情但不具备正确知识的人,所以你可以讲时间并给出完整的答案。

非常感谢您。

在后台执行 npm install

npm install &

然后在 done 行之后,您可以等待所有后台进程完成:

wait

此命令在bash manual中有解释:

Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero.