几年来,我一直在使用我写的这个脚本(由here扩充而来)来打开web浏览器中的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 ==,它会工作,但随后它会启动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.发布于 2015-09-07 04:10:50
不,
if [ $(pgrep -c rtorrent) == 0 ]和
if ! pgrep "rtorrent" /dev/null绝不是“等同的”。
第一个错误地比较了pgrep的标准输出为0,而后者检查pgrep "rtorrent" /dev/null是否返回了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的不可移植的内置[[。
如果依赖于任何输出,建议引用子subshell调用和要匹配的模式,如下所示:
if [ "$(pgrep -c "rtorrent")" = "0" ];如果这仍然没有完成您想让它完成的任务,请查看pgrep -c "rtorrent"的输出。
https://stackoverflow.com/questions/32427528
复制相似问题