Bash脚本意外停止执行(以前工作)

时间:2015-09-06 19:40:33

标签: bash grep

我一直在使用我编写的这个脚本(从here扩充而来)几年来从网络浏览器打开torrent链接。

#!/bin/bash

cd /rtorrent_watch
[[ "$1" =~ xt=urn:btih:([^&/]+) ]] || exit;
echo "d10:magnet-uri${#1}:${1}e" > "meta-${BASH_REMATCH[1]}.torrent"

if [ "$(pgrep -c "rtorrent")" = "0" ]; then
    gnome-terminal --geometry=105x24 -e rtorrent
fi

突然有一天它停止了工作。第一部分仍然有效 - 它保存了一个torrent文件 - 但是if语句没有执行。如果我将条件更改为0 == 0它可以工作,但即使它已经在运行,它也会启动rtorrent。如果我做

#!/bin/bash

cd /rtorrent_watch
[[ "$1" =~ xt=urn:btih:([^&/]+) ]] || exit;
echo "d10:magnet-uri${#1}:${1}e" > "meta-${BASH_REMATCH[1]}.torrent"

if ! pgrep "rtorrent" > dev/null; then
    gnome-terminal --geometry=105x24 -e rtorrent
fi

哪个应该与第一个相同,它也不起作用。如果我只使用if语句创建一个脚本,它可以正常工作。有没有理由在这种情况下pgrep无法执行?

谢谢!

编辑:

$ pgrep -c "rtorrent" | xxd # when rtorrent is not running
00000000: 300a                                     0.
$ pgrep -c "rtorrent" | xxd # when rtorrent is running
00000000: 310a                                     1.

1 个答案:

答案 0 :(得分:2)

没有

if [ $(pgrep -c rtorrent) == 0 ]

if ! pgrep "rtorrent" /dev/null
绝不是"等同于"。

第一个是 - 错误地 - 将pgrep s 标准输出与0进行比较,而后者检查pgrep "rtorrent" /dev/null是否返回了值(即返回值,完全忽略任何值)除<{1}}以外的输出)(这通常意味着&#34;成功&#34;。)

请注意0会因为给出两个参数pgrep"rtorrent"而纾困。你可能想执行

/dev/null

甚至

if ! pgrep "rtorrent" >/dev/null

还要重定向if ! pgrep "rtorrent" >/dev/null 2>&1

另请注意,调用stderr时调用的test实用程序不知道[运算符,c.f。 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html

相反,请使用==运算符,或切换到内置=的非可移植bash

如果依赖于任何输出,建议引用子shell调用和要匹配的模式,如下所示:

[[

如果仍然没有按照您想要的方式执行操作,请查看if [ "$(pgrep -c "rtorrent")" = "0" ]; 的输出。

相关问题