如何保存多个$!到变量中,然后在bash中使用它? [英] How to save multiple $! into variables and use it later in bash?

查看:67
本文介绍了如何保存多个$!到变量中,然后在bash中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取两个后台进程的pids

I want to get the pids of two background processes,

sleep 20 & pid1=$\!; sleep 10 & pid2=$\!; echo "pid1: $pid1, pid2: $pid2"

并获得如下输出:

[1] 124646
[2] 124648
pid1: $!, pid2: $!

我想要获得的输出如下:

the output I desired to get is like:

pid1: 124646, pid2: 124648

任何人都知道为什么并且可以帮助实现这一目标吗?

Anyone know why and can help to achieve this?

[添加2018/01/02]

[add 2018/01/02]

对不起,我的回复很晚,一只手很忙,另一只手是我要验证脚本.

Sorry for really late response, one hand is busy, another is that I want to verify the script.

我要运行的实际脚本如下:

The actual script I want to run is like below:

sh -c "sleep 20 & pid1=$!; sleep 10 & pid2=$!; echo \"pid1: $pid1, pid2: $pid2\""

,因为它将报告bash: !: event not found,所以我尝试添加\并成为:

and as it will report bash: !: event not found, so I tried to add \ and become:

sh -c "sleep 20 & pid1=$\!; sleep 10 & pid2=$\!; echo \"pid1: $pid1, pid2: $pid2\""

为了使问题变得简单,我只是删除了sh -c,而这使它成为了一个完全不同的问题.

and for make the problem simple, I just rmeove sh -c while this make it a quite different problem.

对于我的问题,我发现以下脚本可以工作:

for my problem, I found out that below script will work:

sh -c 'sleep 20 & pid1=$!; sleep 10 & pid2=$!; echo "pid1: $pid1, pid2: $pid2"'

还有另一个问题,如何使以下脚本起作用:

Yet there is another question, how to make below script to work:

name='bob'
# below script reports 'bash: !: event not found' error
sh -c "echo $name; sleep 20 & pid1=$!; sleep 10 & pid2=$!; echo \"pid1: $pid1, pid2: $pid2\"" 
# below script $name will not become bob
sh -c 'echo $name; sleep 20 & pid1=$!; sleep 10 & pid2=$!; echo \"pid1: $pid1, pid2: $pid2\"' 

推荐答案

反斜杠使该值逐字成为字符串$!.不要在作业中加反斜杠.

The backslash is causing the value to be the string $! verbatim. Don't put a backslash in the assignment.

在命令行上,您可能需要临时set +H以避免收到event not found警告;但这只会影响交互式外壳.在脚本中,set -H永远不会处于活动状态(无论如何也将毫无意义).

On the command line, you may want to temporarily set +H to avoid getting event not found warnings; but this only affects the interactive shell. In a script, set -H is never active (and would be meaningless anyway).

(我推测这是您将反斜杠放在第一位的原因.否则,只需将其删除即可.)

(I'm speculating this is the reason you put the backslash there in the first place. If not, simply just take it out.)

这篇关于如何保存多个$!到变量中,然后在bash中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆