2015-09-06 71 views
0

我一直在使用我寫的腳本(從here擴充)多年,以便從Web瀏覽器中打開torrent鏈接。Bash腳本意外停止執行(用於工作)

#!/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. 
+0

請指定'pgrep -c「rtorrent」的輸出| xxd'。 通常情況下,換行符不會導致這類代碼的問題,但也許'bash'或'pgrep'決定嚴格執行。這可能是一個換行問題。 – Ionic

+0

它確實打印換行符,但我用'「$(pgrep -c」rtorrent「| tr -d'\ n')」=「0」'替換了條件,但仍然失敗。 –

+0

你有沒有試過確保rtorrent目前沒有運行,只運行'if! pgrep「rtorrent」> dev/null && gnome-terminal --geometry = 105x24 -e rtorrent'手動?如果這種情況產生了一個新的終端,那麼你應該不用擔心腳本的那部分內容。正則表達式更可能失敗。用'[[​​「$ 1」=〜xt = urn:btih:([^&/] +)]] ||替換該部分{回聲「正則表達式匹配失敗」;出口; }'。 如果出現一些有趣的事情,你的表情就不再匹配了。 – Ionic

回答

2

沒有,

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的非便攜[[內置。

如果任何輸出依託,最好是引用子shell調用和模式,你要匹配,比如:

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

如果這仍不能做你想擁有它做什麼,看看pgrep -c "rtorrent"的輸出。

+0

你說得對,我打錯了 if! pgrep「rtorrent」>/dev/null 在問題中。 我並不知道==不能與[命令一起使用。 如果[「$(pgrep -c」rtorrent「)」=「0」],我用更正的 代替它; ,它仍然不起作用(在這個腳本中)。 pgrep -c「rtorrent」 確實在rtorrent未運行時返回「0」,當它爲「1」時返回。 –