如果程序正在运行,请执行某些操作

Fel*_*ll4 3 command-line bash scripts process

是否可以在终端中输入一些内容,以便在某个程序正在运行时运行命令?例如,if <Libre office is running> then sudo pkill <Libre ofice>

编辑 1:所以我想要做的是在终端中创建一个 if 语句,如果程序正在运行,则运行,如果不是,则不执行任何操作,或执行其他操作。

Joh*_*024 6

“我想要做的是在终端中创建一个 if 语句,如果程序正在运行,则运行,如果不是,则什么也不做,或者做其他事情”

要根据程序的名称确定程序是否正在运行,请使用pgrep. 如果 LibreOffice 的文字处理器正在运行,要执行以下操作:

pgrep soffice.bin >/dev/null && do_something
Run Code Online (Sandbox Code Playgroud)

类似地,如果 LibreOffice 的文字处理器运行,则执行以下操作:

pgrep soffice.bin >/dev/null || do_something
Run Code Online (Sandbox Code Playgroud)

此外,您可以结合使用这两个:

pgrep soffice.bin && do_one_thing || do_another
Run Code Online (Sandbox Code Playgroud)

或者,如果事情变得更复杂,请使用以下if语句:

if pgrep soffice.bin
then
    # command is running
    do_one_thing
    do_one_thing2
else
    # command is not running
    do_another
    do_another2
fi
Run Code Online (Sandbox Code Playgroud)

上述工作是因为pgrep,就像 一样grep,设置了一个有用的退出代码。如果找到一个进程,它会返回一个为零的退出代码(shell 将其解释为逻辑真)。如果不是,则返回 1(shell 将任何非零退出代码解释为 false)。

要找出当前正在运行的所有程序(以及使用什么名称作为 的参数pgrep),请运行ps ax