【问题标题】:BASH - loop errorBASH - 循环错误
【发布时间】:2013-11-24 13:14:51
【问题描述】:

我在 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'

【问题讨论】:

  • 您需要以fi 结束if 语句。
  • 我添加了它,但我在这里有错误 if[["$SERVER" = "$name"]];然后...
  • if[[ 之间应该有一个空格。

标签: bash ssh debian gnu-screen


【解决方案1】:

试试这个:

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

它将使您的变量保持可访问性。 在最后一行中,我们让 screen 和 grep 在子 shell 中运行,并通过匿名文件描述符将它们的输出提供给 while 状态(这种方式不需要子 shell)

另一种方式是:

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

就像,谁在乎它是否在子shell中运行,只要我们能得到我们的变量。在这种情况下,通过回显变量并使用 $() 捕获子外壳回显的输出

一个空字符串被评估为false,所以我们不需要在这个例子中显式地分配它。

【讨论】:

    【解决方案2】:

    好的,现在我有

    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 :

    【讨论】:

    • 是的,因为您强制 while 在子 shell 中运行(因此范围有限)。为了传送到while,bash 需要将它包装在一个子shell 中,否则bash 会传送到self,这是自动完成的,因此会让人惊讶:“那个子shell 是从哪里来的?”。不用担心每个人都被那个咬过。 ;-)
    • 除此之外:ISEXISTS = false 应该是 ISEXISTS=false。作业中不允许有空格
    猜你喜欢
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 2017-04-17
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多