等不在shell脚本中工作?

时间:2017-06-20 10:49:51

标签: bash shell multiprocessing

我正在运行一个for循环,其中一个命令在后台使用&运行。最后,我希望所有命令都返回值..

这是我试过的代码

for((i=0 ;i<3;i++)) {

    // curl command which returns a value   & 
    } 
    wait

//下一段代码

我想获得所有三个返回值,然后继续..但是wait命令不会等待后台进程完成并运行下一部分代码。我需要返回值才能继续..

2 个答案:

答案 0 :(得分:3)

Shell内置的文档可以通过 var deduct = 100; var newMoney = {{user.e_money}} - deduct; var username = getUserName(); //get the current user // send a message to the server that the e-money value has changed socket.emit('update e-money', username, newMoney); console.log("Emitting the data to the server side - emoney: " + newMoney + " with the name money of : " + username); //end clearTimeout(interval); //send the data to the server socket.emit('chat message', getUser()); var interval = setTimeout(function(){ $('.'+getUser()).fadeIn(); },5000); }); socket.on('update e-money response', function (data) { alert("Your money is: "+ data.newMoney); console.log("Your money is: "+ data.newMoney); }); 访问。 //emoney socket.on('update e-money', function (data) { var userName = data.username; var newMoney = data.newMoney; //var query = {"name": userName}; // update the entry on the database User.findOneAndUpdate({"username":userName}, {"$set":{"e_money": "300" }}, { upsert: true, returnOriginal:false }, function (err, doc) { if (err) { console.log("There was an error: " + err); console.log(userName); io.emit('update e-money error', { error: err }); } else { io.emit('update e-money response', { newMoney: newMoney }); console.log(newMoney); } }); }); 收益:

src

这意味着要获得返回状态,您需要保存pid,然后使用help BUILTIN_NAME等待每个pid。

示例:

help wait

示例输出:

wait: wait [-n] [id ...]
    Wait for job completion and return exit status.

    Waits for each process identified by an ID, which may be a process ID or a
    job specification, and reports its termination status.  If ID is not
    given, waits for all currently active child processes, and the return
    status is zero.  If ID is a a job specification, waits for all processes
    in that job's pipeline.

    If the -n option is supplied, waits for the next job to terminate and
    returns its exit status.

    Exit Status:
    Returns the status of the last ID; fails if ID is invalid or an invalid
    option is given.

修改

使用curl,不要忘记传递wait $THE_PIDsl() { sleep $1; echo $1; return $(($1+42)); } pids=(); for((i=0;i<3;i++)); do sl $i & pids+=($!); done; for pid in ${pids[@]}; do wait $pid; echo ret=$?; done )以确保在HTTP请求执行时进程失败:

CURL示例:

0
ret=42
1
ret=43
2
ret=44

CURL示例输出:

-f

答案 1 :(得分:0)

GNU Parallel 是一种很好的方法,可以并行处理curl等高延迟的事情。

parallel curl --head {} ::: www.google.com www.hp.com www.ibm.com

或者,过滤结果:

parallel curl --head -s {} ::: www.google.com www.hp.com www.ibm.com | grep '^HTTP'
HTTP/1.1 302 Found
HTTP/1.1 301 Moved Permanently
HTTP/1.1 301 Moved Permanently

这是另一个例子:

parallel -k 'echo -n Starting {} ...; sleep 5; echo done.'  ::: 1 2 3 4
Starting 1 ...done.
Starting 2 ...done.
Starting 3 ...done.
Starting 4 ...done.