bash - 退出我的脚本中调用的程序

标签 bash

我正在尝试创建一个 bash 脚本,它基本上调用/执行另一个程序,休眠 5 秒,终止该程序,再次休眠 5 秒,然后最终重新启动整个周期。

这是我创建脚本的尝试:

#! /bin/bash

while true
do

someOtherProgram -options..etc.
PID=$!
echo "someOtherProgram initiated"
sleep 5
kill $PID
echo "someOtherProgram killed"
sleep 5
echo "restarting loop"

done

使用此脚本,它可以启动 someOtherProgram 但它卡在那里。我什至没有看到终端上打印出我的 echo "someOtherProgram returned"

我知道这是一个简单的修复,但我刚开始时并不熟悉 bash 脚本。

感谢任何帮助。

最佳答案

您的问题是$!,

"Expands to the process ID of the job most recently 
 placed into the background"

您没有在后台运行someOtherProgram -options..etc.。为此,您需要:

someOtherProgram -options..etc. &

(注意:末尾的&符号&)

目前您的 PID 为空。您可以通过尝试输出它来轻松地自己确认这一点,例如

echo "someOtherProgram initiated (PID: $PID)"

您可以在“特殊参数”“作业控制”下找到有关使用$!和后台进程(异步运行)的详细说明man bash 中的 部分。

关于bash - 退出我的脚本中调用的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49053174/

相关文章:

bash - Git-Bash 运行命令的快捷方式

bash - 我可以在命令之间进行管道传输,并从不同的目录运行程序吗?

Linux按日期排序 "ls -al"输出

java - bash 在命令中强制使用双引号

bash - 从 shell 脚本的行数中提取公共(public)部分文本

mysql - 尝试隔离每个主机的 pt-query-digest

linux - 向 linux 进程发送信号并拦截它们

Bash 工作代码从文件中删除第一行或最后一行

regex - 如何将 vim 正则表达式替换命令转换为 sed 或 awk?

linux - 如何查找和停止/终止从 shell 脚本启动的进程?