我正在尝试编写一个简单的bash脚本,用于在运行和不运行之间切换imwheel。
以下代码是用toggle-imwheel.sh编写的
#!/bin/bash
if pgrep imwheel;
then
# imwheel process found
echo "Killing imwheel process"
killall imwheel
else
# imwheel process not found
echo "Starting imwheel process"
imwheel
fi当pgrep找到某些东西时,它应该返回退出代码0,当什么都没有找到时,它应该返回退出代码1。但是,pgrep似乎正在查找不存在的进程。下面是bash shell的输出:
mrsiliconguy@swift3:~/.imwheel-scripts$ pgrep imwheel <---- notice that no process is running
mrsiliconguy@swift3:~/.imwheel-scripts$ ./toggle-imwheel.sh
9952 <------ ??????
Killing imwheel process
imwheel: no process found
mrsiliconguy@swift3:~/.imwheel-scripts$ ./toggle-imwheel.sh
9955
Killing imwheel process
imwheel: no process found发布于 2020-01-18 00:15:28
你可以试试,如果你运行的是bash toggle-imwheel,你的脚本也应该可以工作。这是因为pgrep将默认尝试匹配命令名。您的脚本的名称称为foo-imwheel.sh,当您通过./foo-imwheel启动它时,pgrep会发现您的脚本本身是匹配的进程。
但是,如果通过bash foo-imwheel或sh foo-imwheel启动,则命令为sh or bash。pgrep与脚本本身不匹配。
您可以使用pgrep -l进行测试,以在输出中列出命令。
发布于 2020-01-18 00:27:56
您可以更改pgrep的正则表达式以精确匹配:
#!/bin/bash
if pgrep '^imwheel$';
then
# imwheel process found
echo "Killing imwheel process"
killall imwheel
else
# imwheel process not found
echo "Starting imwheel process"
imwheel
fi发布于 2020-01-17 23:39:11
出于某些原因,使用sh运行脚本可以正常工作...不完全确定原因。
mrsiliconguy@swift3:~/.imwheel-scripts$ pgrep imwheel
mrsiliconguy@swift3:~/.imwheel-scripts$ sh toggle-imwheel.sh
Starting imwheel process
INFO: imwheel started (pid=10439)
mrsiliconguy@swift3:~/.imwheel-scripts$ pgrep imwheel
10439
mrsiliconguy@swift3:~/.imwheel-scripts$ sh toggle-imwheel.sh
10439
Killing imwheel process
mrsiliconguy@swift3:~/.imwheel-scripts$ pgrep imwheel
mrsiliconguy@swift3:~/.imwheel-scripts$ https://stackoverflow.com/questions/59790449
复制相似问题