在bash脚本

时间:2015-11-26 16:28:25

标签: bash shell process pid

我试图编写一个脚本来获取从bash脚本中获取进程的名称和pid。

示例:

#!/bin/bash
pass=(`command1 | grep .... | tail ... `)&
if [ "$?" = "0" ]; then
    echo "pid of the sub-shell "$!
    echo "pid of the shell "$$       
else
    echo $?
    exit 1
fi

此脚本的输出是

pid of the sub-process 22725
pid of the shell 22724

我的问题是如何从shell脚本获取command1的pid和命令,以及pass变量中命令的结果。

  1. 如果我删除"&"我得到命令(密码)的结果,但不是子shell的pid
  2. 如果我设置"&"我得到了pid而不是密码

1 个答案:

答案 0 :(得分:1)

更多的上下文会有所帮助,例如,为什么在必须编写" command1"时,为什么需要子shell输出command1的名称?首先在子shell中执行它?

如果要求只是获取子shell进程ID及其结果,请将它们输出到不同的行:

temp=$(mktemp)
command1 ... >$temp &
pid=$!
# other activities here
# ...
wait $pid
read result <$temp

然而,问题表明你想要启动子进程(可能是长时间运行),执行其他活动,然后获取其输出。为此尝试命名管道(示例here)或临时文件:

$wpdb->query('select * from ..');