Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 在liunx中打开程序时如何运行bash脚本_Linux_Bash_Ubuntu_Cron - Fatal编程技术网

Linux 在liunx中打开程序时如何运行bash脚本

Linux 在liunx中打开程序时如何运行bash脚本,linux,bash,ubuntu,cron,Linux,Bash,Ubuntu,Cron,当我在Ubuntu上单击NetBeans或DropBox之类的程序时,有没有办法执行bash脚本 并在退出时执行bash脚本 我的想法是在cronjob@reboot上创建bash脚本,每秒检查一次当前进程中是否存在该程序 #!/bin/bash NameOfprogram="NetBeans" while [[ true ]]; do countOfprocess=$(ps -ef |grep $NameOfprogram | wc -l) if [[ $countOfproc

当我在Ubuntu上单击NetBeans或DropBox之类的程序时,有没有办法执行bash脚本 并在退出时执行bash脚本

我的想法是在cronjob@reboot上创建bash脚本,每秒检查一次当前进程中是否存在该程序

#!/bin/bash
NameOfprogram="NetBeans"
while [[ true ]]; do
    countOfprocess=$(ps -ef |grep $NameOfprogram | wc -l)
    if [[ $countOfprocess -gt 1 ]]; then
        #execute bash 
    fi
    sleep 1
done

但是我认为这个想法不是最好的,有没有更好的方法来实现它呢?

更好的方法是将可执行文件封装在脚本中。这意味着您在路径中放置了一个带有程序名的脚本(可能是
$HOME/bin
),Linux将使用该脚本而不是真正的可执行文件

现在,您可以使用以下命令执行实际程序:

/usr/bin/NetBeans "$@"
所以要执行真正的可执行文件,只需将绝对路径放在名称前面。奇怪的
“$@”
也传递了可能有人给脚本的任何参数

围绕这一点做一个循环:

while [[ true ]]; do
    /usr/bin/NetBeans "$@"
done
但是有一个问题:你不能再退出这个程序了。只要您尝试,它就会重新启动。因此,如果您只是想在它崩溃时重新启动:

while [[ true ]]; do
    /usr/bin/NetBeans "$@" && exit 0
done

只要程序因错误退出,它就会重新启动。如果退出,脚本将停止。

这听起来像是针对一个简单问题尝试的错误解决方案…
而[[true]]
是检查字符串“true”是否为空。它适用于无限循环,但在
[[
如何工作方面显示出一些混乱。
而[[false]]
也会有同样的结果。
而true
执行内置的
true
@Ignacio Vazquez Abrams有没有更好的解决方案??不是不知道实际问题是什么。如果你说这是一个糟糕的解决方案,那么最好的解决方案是什么?