2013-11-24 26 views
-1

我有一個腳本在bash:<BASH - 環誤差

SERVER="screen_name" 
INTERVAL=60 
ISEXISTS=false 

screen -ls | grep $'^\t' | while read name _rest ; do 
    if[["$SERVER" = "$name"]]; 
     then echo "YEP" && ISEXISTS=true && break 
    fi 
done 

if $ISEXISTS 
then screen -dmS automessage 
else exit 0 

while true 
do 
screen -S $SERVER -X stuff "TEST\r" 
sleep $INTERVAL 
done 

但是當我嘗試運行它,我有錯誤:

line:13 syntax error near unexpected token `then' 
+0

您需要用'fi'結束'if'語句。 – pfnuesel

+0

我添加它,但我在這裏有錯誤 if [[「$ SERVER」=「$ name」]];然後... – user1366028

+1

在'if'和'[''之間應該有一個空格。 – pfnuesel

回答

0

試試這個:

ISEXISTS=false 
while read name _rest 
do 
    if [[ "$name" == *"$SERVER"* ]]; 
     then ISEXISTS=true 
    fi 
done < <(screen -ls | grep $'^\t') 

這將讓您的變量訪問。 在最後一行,我們讓一個子shell的屏幕和grep運行,並通過一個匿名文件描述符的while statment(這並不需要一個子shell這樣)

另一種方法是養活自己的輸出:

ISEXIST=$( 
      screen -ls | grep $'^\t' | while read name _rest 
      do 
       if [[ "$name" == *"$SERVER"* ]]; 
       then echo "true" 
       fi 
      done 
     ) 

像,誰在乎它是否在子shell中運行,只要我們可以得到我們的變量。在這種情況下,通過回顯變量並通過使用$()

捕獲子外殼回顯中的輸出,因此我們不需要在此示例中顯式分配空字符串。

0

OK現在我有

ISEXISTS = false 
screen -ls | grep $'^\t' | while read name _rest ; do 
    if [[ "$name" == *"$SERVER"* ]]; 
    then ISEXISTS=true 
    fi 
done 

當我將ISEXISTS設置爲true時,這不起作用:F我測試它並在循環中ISEXISTS = true但在外部循環中ISEXISTS = false:<

+0

是的,因爲你強迫'while'在子shell中運行(因此有限的範圍)。爲了管到'while',bash需要將它包裝在一個子shell中,否則bash會自動調用,這是自動完成的,因此出乎意料:「子shell從哪裏來?」。不用擔心每個人都被那個人咬了。 ;-) – thom

+0

除此之外:'ISEXISTS = false'應該是'ISEXISTS = false'。作業中不允許有空格 – thom